0

可能重复:
Backbone.js - 名称更改时未触发更改

在我的以下功能中,控制台显示数据,但没有附加到正文标签,任何人都发现我的问题..

我的 json :

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

代码 :

    (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)
4

1 回答 1

0

问题似乎在这两行:

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

Collection.fetch是一个异步操作。当render您查看时,请求尚未返回,因此您的集合为空。尝试将渲染方法绑定到集合reset事件:

collection.on("reset", this.render, this);
this.collection.fetch();
于 2013-01-18T12:26:22.457 回答