Backbone.js - fetch方法不会触发重置事件

chr*_*r1s 6 backbone.js backbone-events backbone.js-collections

我开始使用Backbone.js并尝试构建我的第一个示例应用程序 - 购物清单.

我的问题是,当我获取项目集合时,重置事件可能不会被触发,因此我的render方法不会被调用.

模型:

Item = Backbone.Model.extend({
  urlRoot : '/api/items',
  defaults : {
    id : null,
    title : null,
    quantity : 0,
    quantityType : null,
    enabled : true
  }
});
Run Code Online (Sandbox Code Playgroud)

采集:

ShoppingList = Backbone.Collection.extend({
  model : Item,
  url : '/api/items'
});
Run Code Online (Sandbox Code Playgroud)

列表显示:

ShoppingListView = Backbone.View.extend({

el : jQuery('#shopping-list'),

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

render : function (event) {
    // console.log('THIS IS NEVER EXECUTED');
    var self = this;
    _.each(this.model.models, function (item) {
        var itemView = new ShoppingListItemView({
            model : item
        });
        jQuery(self.el).append(itemView.render().el);
    });
    return this;
}

});
Run Code Online (Sandbox Code Playgroud)

列表项视图:

ShoppingListItemView = Backbone.View.extend({

tagName : 'li',

template : _.template(jQuery('#shopping-list-item').html()), // set template for item

render : function (event) {
    jQuery(this.el).html(this.template(this.model.toJSON()));
    return this;
}

});
Run Code Online (Sandbox Code Playgroud)

路由器:

var AppRouter = Backbone.Router.extend({

routes : {
    '' : 'show'
},

show : function () {
    this.shoppingList = new ShoppingList();
    this.shoppingListView = new ShoppingListView({
        model : this.shoppingList
    });
    this.shoppingList.fetch(); // fetch collection from server
}

});
Run Code Online (Sandbox Code Playgroud)

申请开始:

var app = new AppRouter();
Backbone.history.start();
Run Code Online (Sandbox Code Playgroud)

页面加载后,从服务器正确获取项目集合,但从不调用ShoppingListView的render方法.我做错了什么?

Eri*_* Hu 27

这是你的问题:

"当模型数据从服务器返回时,它使用set来(智能地)合并获取的模型,除非你通过{reset:true}" Backbone Docs

因此,您希望使用重置选项触发提取:

this.shoppingList.fetch({reset:true}); // fetch collection from server
Run Code Online (Sandbox Code Playgroud)

另外,您可以在视图上定义集合属性:

this.shoppingList = new ShoppingList();
  this.shoppingListView = new ShoppingListView({
     collection : this.shoppingList  // instead of model: this.shoppingList
  });
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢!“ {reset:true}”是解决我的问题的关键。 (2认同)