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

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

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

模型:

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方法.我做错了什么?

解决方法

这是你的问题:

“当模型数据从服务器返回时,它使用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
  });

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...