2012-10-11 21 views
-1

我有问题要取消绑定一个听众,听共享发射器之一:jQuery的解除绑定监听

// 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还是继续工作?

+0

你怎么去那种情况下调用。你的设计必须有设计缺陷 –

+0

你能解释为什么它有缺陷吗?我需要相同的命名空间,但具有不同的数据。 –

回答

0

我找到了更好的解决方案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) { 
     .... 
    } 
}); 

现在trigging a.b.c将与listener1listener2触发。 并解除绑定 - 只有与特定的听众解除绑定,如:

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

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

1

保存参照处理程序,以便以后可以unbind它:

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


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

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

谢谢,看起来像在文档中错过了 –