サーバーからコレクションデータを取得し、コレクションオブジェクトに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