我想從服務器獲取集合數據並將其加載到我的集合對象中,並使用Backbone.js。我想在開始時獲取這些數據,並使用這些數據加載我的html頁面。但是,我從服務器下載的數據沒有正確填充到集合中。收集長度爲零,有誰知道我做錯了什麼?Backbone.js集合不添加對象
(function ($) {
window.Menu = Backbone.Model.extend({});
window.MenuCollection = Backbone.Collection.extend({
model: window.Menu,
initialize: function() {
_.bindAll(this, 'parse');
},
url: function(){
return 'http://localhost:8080/testing/123';
},
parse : function(resp) {
console.log(resp);
// this prints:
// "[{"name":"helloworld1"},{"name":"helloworld2"}]"
this.add(resp);
this.add(new Menu({name:"black perl"}));
console.log(this);
// the length of the object in the console log is 0
}
});
window.MenuView = Backbone.View.extend({
tagName: 'li',
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
$(this.el).html('<span>'+this.model.get('name')+'</span>');
return this;
}
});
window.MenuListView = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
this.model.each(function(menu) {
$(this.el).append(new MenuView({model:menu}).render().el);
});
return this;
}
});
var view;
AppView = Backbone.View.extend({
el: $("body"),
initialize: function() {
this.menus = new MenuCollection();
this.menuListView = new MenuListView({model:this.menus});
view = this.menuListView;
this.menus.fetch({success: function(){console.log("success");
console.log(view.render().el);}});
},
events: {
}
});
var appview = new AppView;
})(jQuery);
我在這裏看不到很多努力來簡化示例代碼。如果您可以向我們展示重現相同問題的非常小版本的代碼,可能會有所幫助。 – fguillen 2012-03-13 15:37:49