扩展Backbone.Collection / View / Models的最佳方法

时间:2012-07-30 13:08:19

标签: javascript backbone.js

我需要使用一组函数扩展backbone.collection:

示例:

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

应该有以下自定义方法:

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

另一方面

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

不应该有这些方法。

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

如何为collection1和collection2扩展Backbone.Collection而不为collection3扩展?

2 个答案:

答案 0 :(得分:10)

你的意思是这样的:

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

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

答案 1 :(得分:4)

遵循Marionette示例,您应该将属性或方法添加到对象类的prototype属性中:

无论如何,以下代码相当于@anto_byrma 但这种方法的优点是您可以以相同的方式扩展集合或模型或视图。

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);