Backbone.js事件未启动

Backbone.js event not fired

本文关键字:启动 事件 js Backbone      更新时间:2023-12-31

我有以下backbone.js代码,用于呈现后端提供的产品列表。问题是AppViewrender方法永远不会被调用,也就是说,当fetch调用完成时,通过this.listenTo(product_list, 'change', this.render);连接的侦听器不会被激发。

有人能告诉我怎么了吗?

$(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();
});

我也遇到了同样的问题,通过查看源代码,我发现集合在获取时不会触发change事件。change事件仅在已更新的模型上激发。由于使用的是reset:true,请尝试侦听reset事件。