2011-09-09 88 views
2

我有問題,當我嘗試從服務器獲取數據到我的骨幹模型。你從我認爲看起來是正確格式化的服務器得到JSON的響應。你能看到它有什麼問題嗎?它看起來像:骨幹:沒有數據添加到模型上獲取()

[{"id":"1","name":"Fawad Hassan","email":"[email protected]"},{"id":"2","name":"Bill 
Gates","email":"[email protected]"},{"id":"3","name":"Steve 
Jobs","email":"[email protected]"},{"id":"4","name":"Naveed 
Ahmad","email":"[email protected]"},{"id":"5","name":"Mr Zee","email":"[email protected]"}] 

我對骨幹項目代碼看起來像這樣,我真的不能找到問題有兩種。

window.AppModel = Backbone.Model.extend({ 
    url: function() { 
     return 'http://dev.local/ci/index.php/site/userpost'; 
    } 
}); 

window.AppContr = Backbone.Collection.extend({ 
    model: AppModel, 
    initialize: function() { 
     this.model = new AppModel; 
    } 
}); 

window.App = new AppContr({name: "Markus"}); 

window.AppView = Backbone.View.extend({ 
    el: $("#content"), 
    initialize: function() { 
     this.render(); 
    }, 
    render: function() { 
     console.log(App.model.toJSON()); 
    } 
}); 

App.model.fetch(); 
window.View = new AppView; 

回答

8

你正在做模型上fetch,但在響應返回集合。這是主要問題。

第二個問題是您在AppView上完全隨機地調用render,即它與model或或collection沒有任何關係。當您渲染視圖時,也許model中沒有任何內容。您應該將渲染綁定到collectionmodelbind。不是每當你叫fetch你的觀點會重新渲染,這是骨幹:)

這裏的主要好處之一而來的代碼:)

window.Person = Backbone.Model.extend({}); 

window.Addressbook = Backbone.Collection.extend({ 
    url: 'http://dev.local/ci/index.php/site/userpost',// declare url in collection 
    model: Person 
} 

window.Addresses = new AddressBook(); 

window.AppView = Backbone.View.extend({ 
    el: $('#content'), 
    initialize: function() { 
     Addresses.bind('reset', this.render); // bind rendering to Addresses.fetch() 
    }, 
    render: function(){ 
     console.log(Addresses.toJSON()); 
    } 
}); 

window.appview = new AppView(); 
Addresses.fetch(); 
+0

那麼如何,如果你正在使用的視圖這種變化渲染一個模型(沒有集合)? – Randy

+0

我遇到了同樣的問題。我忘記集合被提取爲異步... – hellojinjie