Sunday 7 February 2010

jQuery Namespaced Events - exclusive trigger

Namespaced events have been around in jQuery since 1.2, and is fairly well documented here. However, when I was looking at the jQuery (1.3.2) source code the other day, I stumbled across an interesting bit of functionality that doesn't appear to be well documented.

It appears you can also trigger non-namespaced events by providing an exclamation mark to the end of the event name (e.g. "click!"). This will then only trigger events of that type, which are not namespaced. In the source code, this is referred to as exclusive. See the trigger and handle functions.

For example:

$(document).bind("click", function() { console.log("click"); });
$(document).bind("click.foo", function() { console.log("click.foo"); });
$(document).bind("click.foo.bar", function() { console.log("click.foo.bar"); });

$(document).triggerHandler("click");
console.log("---");
$(document).triggerHandler("click.foo");
console.log("---");
$(document).triggerHandler("click.foo.bar");
console.log("---");
$(document).triggerHandler("click!");


/* 
//prints out...
click
click.foo
click.foo.bar
---
click.foo
click.foo.bar
---
click.foo.bar
---
click
*/


197 comments: