Backbone.js Collection Not Adding Objects
Solution 1:
You're misunderstanding how parse works:
parse
collection.parse(response)parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw
responseobject, and should return the array of model attributes to be added to the collection.
So if you're getting [{"name":"helloworld1"},{"name":"helloworld2"}] from the server, you don't even need a parse implementation.
The strange behavior you're seeing with add is more interesting. If we look at fetch, we see this:
fetch: function(options) {
//...
options.success = function(resp, status, xhr) {
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
if (success) success(collection, resp);
};
//...
}
You're calling fetch without the add option set so things happen like this:
collection.parseis called.- Your
parseadds a few things and callsconsole.log. - Your parse doesn't return anything at all.
collection.resetis called to add whatparsereturned.resetwill clear out the collection and then adds nothing becauseparsedidn't return anything.
Some console.log implementations put a live reference in the console, that's why you get an empty collection in the console: console.log(this) ends up showing this after the reset call.
Solution 2:
Actually, another problem you have is that you are not passing "this" into the context of the for loop inside your view rendering. Thus, when you return the "el" element, your html page will be blank without the contents from the server.
Solution 3:
Bear in mind that the parse method as availble from backbone.js 0.9+ version 0.5.3 would not call parse.
Post a Comment for "Backbone.js Collection Not Adding Objects"