I am trying to fetch a collection data from the server and load it into my collection object, with Backbone.js. I want to fetch these data at the start, and load my html page with these data. However, the data I downloaded from the server does not get populated into the collection properly. The collection length is zero, do anyone know what I am doing wrong?
(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);