如何在集合更改时重置此主干视图

How Can I Reset This Backbone View on Collection Change?

本文关键字:视图 集合      更新时间:2023-09-26

如何将此视图绑定到集合更改事件,以便在将新项添加到集合时重置?

KAC.Views.ModuleMainNavigation = Backbone.View.extend(
    {
        tagName: "div",
        id: "",
        className: "",
        template: JST['modules/main_navigation'],
        initialize: function() {
            _.bindAll(this);
        },
        events: {
        },
        render: function () {
            this.$el.html(
                this.template(
                    { 
                        collection : this.collection 
                    }
                )
            );
            return this;
        }
    }
);

您必须侦听更改事件
大多数情况下,这是在initialize函数中完成的。

您可以监听所有事件(型号更改、集合重置、新型号、删除型号):

this.collection.on('change reset add remove', this.render, this);

或者仅针对新型号添加事件:

this.collection.on('add', this.render, this);

另请参阅backbone.js收集事件