简体   繁体   English

Backbone.js事件未被触发

[英]Backbone.js event not fired

I have the following backbone.js code, which is meant to render a product list provided by the backend. 我有以下backbone.js代码,用于呈现后端提供的产品列表。 The problem is that the render method of AppView is never called - ie the listener attached via this.listenTo(product_list, 'change', this.render); 问题是AppViewrender方法永远不会被调用 - 即通过this.listenTo(product_list, 'change', this.render);附加的监听器this.listenTo(product_list, 'change', this.render); is not fired when the fetch call is done. fetch调用完成后不会触发。

Can anyone tell me what is wrong? 谁能告诉我有什么问题?

$(function(){

    Product = Backbone.Model.extend({
        url: '/api/product',
        defaults: {
            name: 'default name'
        }
    });

    // Collection
    ProductList = Backbone.Collection.extend({
        url: '/api/products',
        model: Product,
    });
    product_list = new ProductList();

    // Views
    ProductListView = Backbone.View.extend({
        tagName: 'div',
        initialize: function(){
            this.listenTo(this.model, 'change', this.render);
        },
        render: function(){
            console.log('p:render');
            this.$el.html('<input type="checkbox" value="1" name="' + this.model.get('title') + '" /> ' + this.model.get('title') + '<span>$' + this.model.get('price') + '</span>');
            this.$('input').prop('checked', this.model.get('checked'));

            return this;
        }
    });
    AppView = Backbone.View.extend({
        el: '#list',
        initialize: function(){
            this.list = $('#list');
            this.listenTo(product_list, 'change', this.render);

            product_list.fetch({reset:true});
            console.log('fetch');
        },
        render: function(r) {
            console.log('AppView.render');
            product_list.each(function(product){
                console.log('p:e:render()');
                var view = new ProductListView({ model: product });
                this.list.append(view.render().el);
            });
            return this;
        }
    });

    new AppView();
});

I had this same issue, and I discovered by looking at the source that collections don't fire a change event when they fetch. 我遇到了同样的问题,我通过查看源代码发现,当它们获取时,集合不会触发change事件。 The change event is only fired on models that have been updated. 仅在已更新的模型上触发change事件。 Since you are fetching with reset:true , try listening for the reset event. 由于您使用reset:true进行提取,请尝试侦听reset事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM