2011-08-31 96 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

相關問題