2012-07-30 21 views
1

我需要與函數的集合延長backbone.collection:最好的方式來擴展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 

如何擴展Backbone.Collection僅用於collection1和collection2而不用於collection3?

回答

4

繼木偶例子中,你應該屬性或方法添加到對象類的原型屬性:

反正下面的代碼就相當於@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); 
+0

很簡單,當你看到它完成:) – Deminetix 2013-11-18 03:48:08

10

你的意思是這樣的:

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

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