骨干收集 - 是创建()实例方法



我有类似骨干模型的集合:

window.Message = Backbone.Model.extend({});
window.MessageCollect = Backbone.Collection.extend({ model: Message, url: '/messages'});

为什么我必须实例化新集合才能调用Create()?如果我在MessageCollect上调用CREATE(),我会收到一个无方法错误。

window.Messages = new MessageCollect;
function makeMessage(){ Messages.create({title:'first message', sender:user_name}); }
//ok
function makeMessageTwo(){ MessageCollect.create({title:'first message', sender:user_name}); }
//Object function (){ parent.apply(this, arguments); } has no method 'create' 

因为backbone.collection-是类,而不是实例。当您调用Backbone.Collection.collection.extend时,您会扩展基类,您不会创建新实例。Collection.Create() - 在集合实例中创建新模型的方法。当您没有实例时,如何将新模型附加到其中?

更好地了解这里发生的事情,这是_.extend做的:

将源对象中的所有属性复制到 目标对象,然后返回目标对象。这是秩序的, 因此,最后一个来源将覆盖同名的属性 以前的参数。

so backbone.collection.collection.extend只是将您定义的源对象采用并将其属性添加到backbone.collection。以使其使用所定义的内容进行增强,然后将其分配到您的变量窗口中。

查看骨干代码,它的作用是,它"扩展"了使用这些方法创建,添加,tojson等的收集的 prototype ...因为它添加到原型中,然后适用于实例 backbone.collection而不是功能本身,因为这是原型

函数对象从function.protype继承。修改 function.prototype对象都传播到所有函数实例。

在某种程度上,它等效于此简单代码:

var Car = function(name){
    this.name = name;
}
var ford = new Car("ford");
Car.prototype.drive = function(){
    console.log("drive");
}
ford.drive(); //possible
Car.drive(); // not possible: Uncaught TypeError: object has no method 'drive'
​

最新更新