jQuery事件命名空间中所有事件的一个监听器? [英] One listener for ALL events in jQuery event namespace?
问题描述
如:
$ pre $
$(window).on(。event_namespace,function(e){
// handler
});
$(window).trigger(testEvent.event_namespace);
$(window).trigger(testEventTwo.event_namespace);
预期的行为是监听器捕获使用指定的命名空间触发的任何事件...
最终目标只是能够听取一组事件,这些事件实际上将被我没有访问权限的代码触发。我想说,只需将你的事件添加到这个命名空间,然后能够捕获那些,而不需要知道事件名称本身;只有命名空间。
可能?
/ p>
尝试
var ns =.event_namespace,log = [ ]。
//位于脚本块底部的块下方,
//在`n`事件附加到`n`窗口后,文档元素
//在
$(窗口,文档,*)上面查看具有`ns`命名空间的
//附加到`window,document',*`上的事件on(event,function (e,ns,type){
//当事件发生`ns'时,做某事
log.push([ns,type]);
$(#log)。 html(type,namespace:+ log.slice(-1)
+< br> total< i>+ ns +< / i>事件:
+ .length)
});
//如果动态元素,事件随后附加,
//重新运行此块,将这些元素添加到这些元素
$ .each([window,document ,$(*)],function(k,v){
if($ ._ data(v,events)!== undefined){
$ .each($ ._ data v,events),function(key,val){
if(val [0] .namespace === ns.slice( - (ns.length -1))){
$( v).on(key + ns,function(e){
$(e.target).trigger(event,[e.namespace,e.type])
})
}
})
}
});
jsfiddle http://jsfiddle.net/guest271314/s87j4o6r/4/
I know I have the ability to namespace events using jQuery's, $.fn.on, off and trigger functions. Is it possible to set up a handler that is able to listen to ALL events in a certain namespace?
Such as:
$(window).on(".event_namespace", function(e){
//handler
});
$(window).trigger("testEvent.event_namespace");
$(window).trigger("testEventTwo.event_namespace");
With the intended behavior being that the listener would capture any event triggered with the specified namespace...
The end-goal is simply to be able to listen to a group of events that will actually be fired by code that I don't have access too. I'd like to be able to say, "just add your event to this namespace," and then be able to capture those without needing to know the event names themselves; only the namespace.
Possible?
Edit, Updated
Try
var ns = ".event_namespace", log = [];
// place below block at bottom of script block ,
// after `n` events attached to `n` window, document, elements
// listen for events having `ns` namespace ,
// attached to `window, document, "*"` , above
$(window, document, "*").on("event", function(e, ns, type) {
// do stuff when event having `ns` occurs
log.push([ns, type]);
$("#log").html("type, namespace: " + log.slice(-1)
+ "<br> total <i>" + ns + "</i> events: "
+ log.length)
});
// if dynamic elements , events later attached ,
// re-run this piece to add `event` event to those elements
$.each([window, document, $("*")], function(k, v) {
if($._data(v, "events") !== undefined) {
$.each($._data(v, "events"), function(key, val) {
if (val[0].namespace === ns.slice(- (ns.length -1))) {
$(v).on(key + ns, function(e) {
$(e.target).trigger("event", [e.namespace, e.type])
})
}
})
}
});
jsfiddle http://jsfiddle.net/guest271314/s87j4o6r/4/
这篇关于jQuery事件命名空间中所有事件的一个监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!