javascript - Backbone.js 事件未触发

标签 javascript backbone.js

我有以下 backbone.js 代码,用于呈现后端提供的产品列表。 问题是 AppViewrender 方法从未被调用 - 即通过 this.listenTo(product_list, 'change', this.render); 附加的监听器; 不会在 fetch 调用完成时触发。

谁能告诉我哪里出了问题?

$(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 事件。

关于javascript - Backbone.js 事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20314720/

相关文章:

javascript - 如何在单独的js文件中创建Backbone View

javascript - 主干自定义事件 : getting caller object

backbone.js - Backbonejs : backbone is not defined error

javascript - 如何在封闭的 Dojo Titlepane 中垂直居中内容?

javascript - 如何在DotNetNuke(DNN)中只加载一次fancybox(JS已经包含在主题和模块中)

javascript - 通过python在网络浏览器上显示arduino串口数据

javascript - 如何在 javascript 类中定义公共(public)属性?

javascript - Angularjs:如何 ng-repeat 具有也是数组的字段的对象数组?

javascript - 主干 View 事件在重新渲染后不起作用

javascript - 如何使用 Backbone Collection 获取此 JSON 结果?