this.unbind 与 this.$el.unbind 在 backbone js 中有什么区别

What is the difference between this.unbind vs this.$el.unbind in backbone js

我在 backbone 视图和 this.destoryview() 方法中绑定了一些事件,我调用了 this.unbind()。但它不是解除绑定事件。当某些事件发生时,它会调用 bounded 方法两次。

然后我将 this.unbind() 调用更改为 this.$el.unbind(),然后它正常工作。

events:{
        'click #closeButton' : 'clearSearch',
        // some events
    },

    initialize: function(options){
        this.container = options.container;         
    },

    render: function() {

        if(this.oSearchContext.isAdvancedSearchEnabled() == true)
        {
            this.$el.html(this.advancedSearchSummaryViewTemplate);              
        }
        else
        {
            this.$el.html(this.advancedSearchTemplate);
        }           
        this.container.append(this.$el);
    },

使用 this.unbind()

的 destroyView 方法
destroyView : function()
    {
        if ( this.oAdvancedSearchSummaryView )
            this.oAdvancedSearchSummaryView.destroyView();

        if ( this.oAdvancedSearchDetailsView )
            this.oAdvancedSearchDetailsView.destroyView();

        // unbind all events
        this.unbind();   // this.$el.unbind() working perfectly

        // empty the rendered element
        this.$el.empty();
    }

能否请您解释一下这两种方法之间的区别。

我建议使用 BackbonelistenTo:

而不是使用 bind
view.listenTo(model, 'change', view.render);

一旦view被销毁,所有绑定将自动解除(解除绑定);

您使用 view.bind(或现代 view.listenToview.on)来订阅另一个 backbone 组件,例如在 backbone型号。

您使用 view.$el.bind(或现代的 view.$el.on)来收听 DOM 中的用户交互。

同样的逻辑适用于 unbind 或现代 off

相似的语法和 API,不同的目的。