骨干事件不触发方法

时间:2013-11-22 13:20:01

标签: javascript backbone.js

在事件执行后仍然绑定了骨干事件,在触发器

之后没有执行object.off

pfb代码摘要

var object = _.extend({}, Backbone.Events);

object.off('app:test:load', function() {
    console.log("========my foot=======");
}, this);
object.on('app:test:load', function () {
    //fn calls
});

object.trigger('app:test:load');

欢迎所有的想法,提前谢谢。

2 个答案:

答案 0 :(得分:2)

此代码存在多个问题:

  • off 方法在注册函数之前被称为,因此可以理解,该触发器将调用日志或其他调用
  • 匿名函数传递给 on 。只能使用 off 功能
  • 的不同覆盖删除匿名函数
  • 将此传递到 off ,对于以这种方式编写的代码,将指向父对象(可能是偶数窗口),所以代码实际上会尝试从其他东西中删除回调,而不是 object

可能会对这个问题有所了解的工作实例:

// create object which support events
var object = _.extend({}, Backbone.Events);

// define function as non-anonymous
var doAction = function () {
     console.log("========my foot=======");
};

// function has to be registered first (cannot remove something that is not there)
object.on('app:test:load', doAction);

// register another function to illustarate removal of anonymous functions
object.on('app:test:load', function(){
    console.log("from anonymous");
});

// will invoke both functions
object.trigger('app:test:load');

// example 1: only remove this particular function for this particular trugger
object.off('app:test:load', doAction);

// will invoke only anonymous, since first one was removed
object.trigger('app:test:load');

// example 2: only remove ALL registered functions for this trigger
object.off('app:test:load');

// will not write anything
object.trigger('app:test:load');

答案 1 :(得分:0)

我认为你在谈论僵尸对象,这在Derick Bailey中有解释 - 帖子

http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/

这意味着对代码的某些部分有引用,而off方法不会删除它。