Skip to content Skip to sidebar Skip to footer

Extending Backbone.collection Prototype

Following on from this question, I'm trying to augment Backbone.Collection with some custom methods. However, I'm getting some inconsistent behaviour between the console and the so

Solution 1:

You are mixing up a few key concepts which is why you aren't seeing the behavior that you expect, which is more a fundamental javascript question and not entirely related to backbone.

Consider the following constructor:

varKlass = function() {};

You can invoke that constuctor using the new keyword to get an instance from that constructor.

var klassInstance = new Klass();

Now, lets say I wanted to add a method that was available to all of the instances that are derivied from that constructor. For that I can use the prototype object.

Klass.prototype.instanceMethod = function() { alert('hi'); };

Then I should be able to invoke that method using the following:

klassInstance.instanceMethod();

However, I can also add a static function – and I use the term loosely in this context – to the constructor itself, which can be invoked without having an instance.

Klass.staticMethod = function() { alert('yo!'); };

This method will be available directly off the constructor, but will not be available – directly – off of instances.

For example:

klassInstance.staticMethod == undefined

So what's really wrong with your test is that you are adding a method to the prototype – a method that will be available to all instances of that "class" – but in your test you are testing for a method directly on the "class" itself. Which is not the same thing.


An aside, though relevant, Backbone.js provides a built in mechanic to create "sub-classes" of thier built in types. This is the static.extend() method. This provides you a simple way to add your own functionality to the base Backbone classes.

In your case you would want to do something like:

varMyCollection = Backbone.Collection.extend({
    extract: function() {
        // do whatever
    }
}) 

Then, you can create instances of your new classes, which will have an .extract() method on them by saying:

var coll = new MyCollection();
coll.extract();

TL;DR;

Ultimately – back to your original question – if you want a method that will be available on all instances of a particular class, then your test is incorrect. You either need to new up an instance to test against:

test('extending backbone', function () {
    var col = newBackbone.Collection();
    ok(typeof col.extract == 'function');
});

Or check the prototype directly for a method – this is subtlely different in the fact that the prototype object is not the only for an object to get a method.

test('extending backbone', function () {
    ok(typeofBackbone.Collection.prototype.extract == 'function');
});

Solution 2:

make sure backbone.js and underscore.js is fully loaded before doing the tests.

Post a Comment for "Extending Backbone.collection Prototype"