Backbone.js的 - 获取的方法不会触发复位事件 [英] Backbone.js - fetch method does not fire reset event

查看:183
本文介绍了Backbone.js的 - 获取的方法不会触发复位事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Backbone.js的开始,试图建立我的第一个示例应用程序 - 购物清单

I'm beginning with Backbone.js and trying to build my first sample app - shopping list.

我的问题是,当我取物品的收集,复位事件是不是可能解雇,所以我的渲染方法没有被调用。

My problem is when I fetch collection of items, reset event isn't probably fired, so my render method isn't called.

型号:

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方法永远不会被调用。我做错了吗?

After page load, collection of items is correctly fetched from server but render method of ShoppingListView is never called. What I am doing wrong?

推荐答案

下面是你的问题:

当从服务器模型数据的回报,它使用设定为(智能)合并获取的车型,除非你传递{重置:真正}的骨干文档

" When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}" Backbone Docs

所以,你想火与复位选项获取:

So, you want to fire the fetch with the reset option:

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


顺便说一句,你可以定义在视图集合属性:

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

这篇关于Backbone.js的 - 获取的方法不会触发复位事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆