【问题标题】:jQuery unbind listenerjQuery 解除绑定监听器
【发布时间】:2012-10-11 08:29:59
【问题描述】:

我无法解除绑定一个侦听共享发射器之一的侦听器:

// this is emitter. Fire always in a.b.c namespace but with different parameters 
$(document).trigger("a.b.c", {
    p: 1,
    p2: ...

});

// listener 1
$(document).bind("a.b.c", function(e, object) {
    if (object.myParam) {
        ....
    }
});

// listener 2
$(document).bind("a.b.c", function(e, object) {
    if (object.anotherParam) {
        ....
    }
});

如何解除监听器 2 的绑定,让监听器 1 继续工作?

【问题讨论】:

  • 你是怎么遇到这种情况的。你的设计一定有设计缺陷
  • 你能解释一下为什么它是缺陷吗?我需要相同的命名空间,但数据不同。

标签: events triggers event-handling jquery


【解决方案1】:

保存对处理程序的引用,以便您以后可以unbind它:

var listener = function(e, object) {
    if (object.anotherParam) {
        ....
    }
};


$(document).bind("a.b.c", listener);

// sometime later:
$(document).unbind("a.b.c", listener);

【讨论】:

    【解决方案2】:

    我找到了更好的解决方案Namespaced Events

    // this is emitter. Fire always in a.b.c namespace but with different parameters 
    $(document).trigger("a.b.c", {
        p: 1,
        p2: ...
    
    });
    
    // listener 1
    $(document).bind("a.b.c.listener1", function(e, object) {
        if (object.myParam) {
            ....
        }
    });
    
    // listener 2
    $(document).bind("a.b.c.listener2", function(e, object) {
        if (object.anotherParam) {
            ....
        }
    });
    

    现在触发a.b.c 将触发listener1listener2。 并解除绑定 - 只需解除与特定侦听器的绑定,例如:

    $(document).unbind("a.b.c.listener1");
    

    在这种情况下,listener2 将被保留,并且能够通过命名空间 a.b.c 调用

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 1970-01-01
      • 2015-09-20
      • 2011-01-13
      • 1970-01-01
      • 2014-08-30
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多