2011-08-31 99 views
4

主干未使用为集合指定的模型。我肯定错过了什么。Backbone.js未使用集合模型值

App.Models.Folder = Backbone.Model.extend({ 
    initialize: function() { 
    _.extend(this, Backbone.Events); 

    this.url = "/folders"; 
    this.items = new App.Collections.FolderItems(); 
    this.items.url = '/folders/' + this.id + '/items'; 
    }, 

    get_item: function(id) { 
    return this.items.get(id); 
    } 
}); 

App.Collections.FolderItems = Backbone.Collection.extend({ 
    model: App.Models.FolderItem 
}); 

App.Models.FolderItem = Backbone.Model.extend({ 
    initialize: function() { 
    console.log("FOLDER ITEM INIT"); 
    } 
}); 


var folder = new App.Models.Folder({id:id}) 
folder.fetch(); 

// later on change event in a view 
folder.items.fetch(); 

该文件夹被加载,然后加载项目,但它们不是FolderItem对象,并且从不调用FOLDER ITEM INIT。它们是基本的模型对象。

我错过了什么?我应该这样做吗?

编辑: 不知道为什么这项工作与文档,但下面的作品。主干5.3

App.Collections.FolderItems = Backbone.Collection.extend({ 
    model: function(attributes) { 
    return new App.Models.FolderItem(attributes); 
    } 
}); 

回答

7

问题是您的模型与集合的声明顺序。基本上,你需要首先定义模型。

App.Models.FolderItem = Backbone.Model.extend({...}); 

App.Collections.FolderItems = Backbone.Collection.extend({ 
    model: App.Models.FolderItem 
}); 

原因是骨干对象是用对象字面值语法定义的,这意味着它们在定义后立即被计算。

这段代码的功能是相同的,但说明了对象字面性质:

var folderItemDef = { ... }; 

var folderItemsDef = { 
    model: App.Models.FolderItem 
} 

App.Models.FolderItem = Backbone.Model.extend(folderItemDef); 

App.Collections.FolderItems = Backbone.Collection.extend(folderItemsDef); 

,你可以在这个例子中看到folderItemDef和folderItems防守都是对象常量,它有自己的key: value对立即评估后的定义的文字。

在您的原始代码中,您首先定义了集合。这意味着App.Models.FolderItem在定义集合时未定义。所以你基本上是这样做的:

App.Collection.extend({ 
    model: undefined 
}); 

通过移动集合定义上述模型定义,不过,收集就能找到模型,它会被正确关联。

FWIW:设置集合模型的函数版本工作的原因是该功能在应用程序执行并且模型被加载到集合中之前不会被评估。在这一点上,JavaScript解释器已经找到了模型的定义,并正确加载它。

+0

啊,这是有道理的。谢谢! – Candland

+0

这让我感到很开心。它造成了非常神秘的错误。我认为这应该在文档中突出显示。 – UpTheCreek

相关问题