Lorraine Bernard
Lorraine Bernard

Reputation: 13400

the best way to extend a Backbone.Collection/View/Models

I need to extend the backbone.collection with a collection of functions:

example:

var collection1 = Backbone.Collection.extend({});
var collection2 = Backbone.Collection.extend({});

should have the following custom methods:

console.log(collection1.method1); // function () {}
console.log(collection1.method2); // function () {}

On the other hand

var collection3 = Backbone.Collection.extend({});

should not have these methods.

console.log(collection3.method1); // undefined

How can I extend the Backbone.Collection just for collection1 and collection2 and not for collection3?

Upvotes: 1

Views: 3369

Answers (2)

antonjs
antonjs

Reputation: 14318

Following the Marionette example you should add properties or methods to the prototype property of an object class:

Anyway the following code is equivalent to @anto_byrma.
But the advantage of this approach is that you can extend collection or model or view in the same way.

var obj = {
    method1: function() {},
    method2: function() {}
};

var collection1 = Backbone.Collection.extend({});
var collection2 = Backbone.Model.extend({});
var collection3 = Backbone.Collection.extend({});

_.extend(collection1.prototype, obj);
_.extend(collection2.prototype, obj);

Upvotes: 4

anton_byrna
anton_byrna

Reputation: 2555

Do you mean something like this:

var CustomCollection = Backbone.Collection.extend({
    method1: function() {},
    method2: function() {}
});
var collection1 = CustomCollection.extend({});
var collection2 = CustomCollection.extend({});

var collection3 = Backbone.Collection.extend({});

Upvotes: 10

Related Questions