Skip to content Skip to sidebar Skip to footer

Backbone.js Collection Not Adding Objects

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

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 response object, 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:

  1. collection.parse is called.
  2. Your parse adds a few things and calls console.log.
  3. Your parse doesn't return anything at all.
  4. collection.reset is called to add what parse returned.
  5. reset will clear out the collection and then adds nothing because parse didn'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"