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

时间:2013-04-11 21:37:01

标签: backbone.js backbone-events backbone.js-collections

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

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

型号:

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

收集:

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

列表视图:

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;
}

});

列出项目视图:

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;
}

});

路由器:

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
}

});

申请开始:

var app = new AppRouter();
Backbone.history.start();

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

2 个答案:

答案 0 :(得分:27)

这是你的问题:

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

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

this.shoppingList.fetch({reset:true}); // fetch collection from server

另外,您可以定义a collection attribute on a view

this.shoppingList = new ShoppingList();
  this.shoppingListView = new ShoppingListView({
     collection : this.shoppingList  // instead of model: this.shoppingList
  });

答案 1 :(得分:1)

您使用的是Backbone 1.0吗?如果没有,请忽略这一点,否则,您可能会发现文档中有关Collection#fetch方法有趣的内容。

引用更改日志:

重命名集合的”更新“以设置,与类似的model.set()并行,并与reset对比。它现在是获取后的默认更新机制。如果你想继续使用”重置“,传递{reset:true}

所以基本上,你不是在reset而是update,因此没有reset事件被触发。