unbin绑定主干事件

时间:2013-05-01 03:26:26

标签: javascript backbone.js

如果我在对象上有事件聚合器,

eventAggregator: _.extend({}, Backbone.Events),

对于模态视图,我基本上让模态视图的演示者监听模态视图的事件。

this.eventAggregator.on('modal:close', function () {
console.log('do some clean up');
});

当模态视图消失时,我调用

this.unbind(); 

这会删除所有事件吗?或者我需要做一些像

这样的事情
this.eventAggregator.off('modal:close');

提前致谢!

3 个答案:

答案 0 :(得分:2)

在最近的Backbone中有listenTohttp://backbonejs.org/#Events-listenTo),因此您可以通过这种方式订阅活动:

this.listenTo(this.eventAggregator, 'modal:close', function () {
    console.log('do some clean up');
})
this.listenTo(this.model, 'change', this.doSomeStuff);

然后,如果您需要取消订阅,只需将其命名为:

this.stopListening();

或者使用view.removehttp://backbonejs.org/#View-remove)删除您的观点,它会在引擎盖下调用view.stopListening

答案 1 :(得分:1)

o.unbind()o内的对象一无所知,只知道使用o(AKA o.on)绑定到o.bind的内容。所以不,this.unbind()对于与this.eventAggregator绑定的事情不会做任何事情,你必须:

this.eventAggregator.unbind();
this.unbind();

清除这两个清单。

答案 2 :(得分:0)

如果你想使用on / off来绑定/取消绑定事件,你可以这样做。

//declare some global object to get the scope.
window.eventAggregator = _.extend({}, Backbone.Events);

现在在骨干视图中:

var SomeView = Backbone.View.extend({
    el : 'body',
    initialize : function() {

        //pass the context as this object
        eventAggregator.on('modal:close', function(data) {
            console.log('Clean up');
            eventAggregator.off('modal:close', null, this);
        }, this);
    }
});

eventAggregator.off('modal:close', null, this);它可以帮助您关闭绑定到“此”当前视图对象的事件。

相关问题