backbone.js not appending elements, still the data

2019-08-22 02:13发布

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)

标签: backbone.js
1条回答
爷、活的狠高调
2楼-- · 2019-08-22 02:58

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();
查看更多
登录 后发表回答