0

Possible Duplicate:
Backbone.js - change not triggering while the name change

In my following function, console show the datas, but nothing is appending to body tag, any one find me the issue..

my json :

[
    {name:'student4'},
    {name:'student5'},
    {name:'student6'}
]

code :

    (function($){   
var model = Backbone.Model.extend({
  defaults:{
    name:'default name'
  }
});

var collection = Backbone.Collection.extend({
  model:model,
  url: 'data/names.json'
});



var itemViews = Backbone.View.extend({
  tagname:'li',
  render:function(){
    this.$el.html(this.model.get('name'));
    return this;
  }  
})

var view = Backbone.View.extend({
  el: $("#contacts"),
  initialize:function(){
    this.collection = new collection();
    this.collection.on("reset", this.render, this);
    this.collection.fetch();
  },
  render:function(){
    var that = this;
    _.each(this.collection.models, function(item){
      that.renderName(item);
    })
  },
  renderName:function(item){
    var itemView = new itemViews({model:item});
    this.$el.append(itemView.render().el); //nothing rendering
  }
});


var stView = new view();

})(jQuery)
Community
  • 1
  • 1
3gwebtrain
  • 14,640
  • 25
  • 121
  • 247
  • At which place do you console.log the collection? I am afraid your JSON data to be parsed into a collection must be like `[{name:'student4'},{name:'student5'},...]` without the extra `{names:[]}` – Amulya Khare Jan 18 '13 at 12:04
  • i tried, no luck. especially on each, i consoled nothing is appear, but in case if i simply console the collection it show the datas, in case of request data show the object as well – 3gwebtrain Jan 18 '13 at 12:08
  • I would try doing .fetch().then(function(){ that.render()}); – Dennis Rongo Jan 19 '13 at 10:28

1 Answers1

0

The problem appears to be in these two lines:

this.collection.fetch(); //it seems it's not fetching;
this.render();  

Collection.fetch is an asynchronous operation. By the time you render your view, the request has not yet returned, so your collection is empty. Try binding the render method to the collections reset event instead:

collection.on("reset", this.render, this);
this.collection.fetch();
jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • i updated, but the render function not at all called – 3gwebtrain Jan 18 '13 at 12:53
  • @3gwebtrain, changed my answer slightly. The previous version should've worked as well, but there were some complexities thay may have caused it to fail. The `reset` event is simpler. – jevakallio Jan 18 '13 at 13:44
  • i updated the coding, still not work. let me update the hole code again for your view. if possible can you put me on fiddle – 3gwebtrain Jan 18 '13 at 13:54
  • There may be some problem with the html. See if you do have an element with `id="contacts"`. – Amulya Khare Jan 18 '13 at 14:11