【发布时间】:2012-03-12 21:59:30
【问题描述】:
我正在尝试使用 Backbone.js 从服务器获取集合数据并将其加载到我的集合对象中。我想在开始时获取这些数据,并用这些数据加载我的 html 页面。但是,我从服务器下载的数据没有正确填充到集合中。集合长度为零,有谁知道我做错了什么?
(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);
【问题讨论】:
-
我没有看到在尝试简化示例代码方面付出了太多努力。如果您能向我们展示一个重现相同问题的非常小的代码版本,将会很有帮助。
标签: javascript backbone.js underscore.js