0

I'm new to Backbone. Can you give me a hint what am I missing here?

here is my model:

var Item = Backbone.Model.extend({

  url: 'json/item.json',

  parse: function(response){
    return response.item;
  },
});

var item = new Item();
item.fetch();

in console "item.toJSON();" shows the result as expected - id, title etc. But when item is passed through view to template

...
this.$el.append( template( item.toJSON() ) );
...

it can't pick any of the attributes - e.g. item.title -> undefined.

json file looks like this:

{
"item":{
    "title": "something something",
     .....
     }
}
  • You have to show your View definition – hindmost Apr 20 '15 at 21:32
  • but I mean View works fine, I assume it has something to do with fetching? Because if I add: var newItem = item.toJSON(): in the console I will get an empty object: newItem Object {} but then again from the console "item.toJSON();" shows the full object as it should be. – flawlessvictory Apr 20 '15 at 21:36
  • u'd better to attach full View code, but i think problem may be caused by mistake in this line: `this.$el.append( template( item.toJSON() ) );` try to use `this.$el.append(_.template( template_html, item.toJSON() ) );` – Evgeniy Apr 21 '15 at 05:58
  • @Evgeniy Since Underscore 1.7.0, Underscore templates no longer accept an initial data object. `_.template` always returns a function now. See http://underscorejs.org/#changelog – nikoshr Apr 21 '15 at 07:56
  • @flawlessvictory Probably closely related to http://stackoverflow.com/questions/9584870/backbone-js-fetch-not-actually-setting-attributes/9585427#9585427 – nikoshr Apr 21 '15 at 07:57
  • @flawlessvictory And for the console showing the data http://stackoverflow.com/a/11463190/1071630 – nikoshr Apr 21 '15 at 07:58
  • @nikoshr, many thanks, missed that – Evgeniy Apr 21 '15 at 08:01

1 Answers1

0

When you call:

var item = new Item();
item.fetch();

This code is probably not synchronous, correct?

Therefore, the fetch has not finished yet when you immediately try to render it!

You can see the object in the console because it's already populated.

Your fetch probably should accept a callback or return a Promise in order to let you know when fetching is done.

var item = new Item();
item.fetch().then(function(fetchedItem){
  console.log(item === fetchedItem) // true
  this.$el.append( template( item.toJSON() ) );
}.bind(this));
Guilherme Rodrigues
  • 2,818
  • 1
  • 17
  • 22