0

I am a Backbone.js newbie and I'm just playing around with it. I would like to know how the model is related with the View when using urlRoot. I'm using a local restful service. When calling 'api/feed/57' I get the following JSON result:

{"id":"57","name":"Speakers","name_desc":null,"url":"http:\/\/speakers.com\/feed\/","category":"1","favicon":"http:\/\/g.etfv.co\/http%3A%2F%2Fspeakers.com%2F","last_update":"2013-09-20 12:57:25","insert_date":"0000-00-00 00:00:00"}

What I want to achive is to have the values retrieved displayed by the view. When trying so, the default values are displayed and not the values retrieved from the urlRoot. I used a console.log(name) to verify if the json service is working properly. It seems so, because "speakers" is shown in the debug. Any idea what I'm doing wrong? The following code is used:

var Feed = Backbone.Model.extend({
    urlRoot: 'api/feed',
    defaults: {
        name: 'Test',
        name_desc: 'Test',
        url: ''
        }
});

var feedItem = new Feed({id: 57});

feedItem.fetch({
    success: function (feedItem) {
        var name = feedItem.get('name');
        console.log(name);
    }
})

var FeedView = Backbone.View.extend({
   tagName: 'li',

   initialize: function(){
     this.render();
   },

   render: function(){
     this.$el.html( this.model.get('name') );
  }
});

var FeedView = new FeedView({ model: feedItem });
FeedView.el;
$(document.body).html(FeedView.el);
Erhnam
  • 901
  • 2
  • 13
  • 23

1 Answers1

0

First, you are overriding your View, choose a different name to store the instance,

var feedView = new FeedView({ model: feedItem });
feedView.render();
$(document.body).html(feedView.el);

Second, the fetch is an asynchronous call so you need to wait for it to complete before rendering,

 initialize: function(){
    this.listenTo(this.model, 'change', this.render);
 },

Now, when your model changes, your render function will be called and update the view with the correct values.

Andrew
  • 13,757
  • 13
  • 66
  • 84