Backbone.js - fetch 方法不会触发重置事件 [英] Backbone.js - fetch method does not fire reset event

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

问题描述

我开始使用 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 的 render 方法.我做错了什么?

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

推荐答案

这是你的问题:

" 当模型数据从服务器返回时,它使用 set 来(智能地)合并获取的模型,除非您传递 {reset: true}" 主干文档

" 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 - fetch 方法不会触发重置事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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