서버에서 컬렉션 데이터를 가져와 Backbone.js를 사용하여 컬렉션 객체에로드하려고합니다. 이 데이터를 처음부터 가져오고이 데이터가있는 HTML 페이지를로드하려고합니다. 그러나 서버에서 다운로드 한 데이터가 컬렉션에 올바르게 채워지지 않습니다. 컬렉션 길이가 0입니다, 내가 뭘 잘못하고 있는지 아는 사람 있습니까?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