jQuery Event Handler Adapter

Bridging the Gap

Old version of jQuery are still being used (<= 1.6) and those versions do not support the new “on” method of attaching event handlers to elements. If you were authoring jQuery plugins and want to ensure compatibility when working with events then you would want to write an adapter inside your plugin.

The adapter works by performing a check to see if the “on” method is supported. If it is supported, then it is used, otherwise the older “bind” method is used instead. However, regardless of which method is supported both “on” and “bind” will be alias. The alias acts as a wrapper and delegates to which method is supported.

Alias After Checking
1
2
3
4
5
6
7
8
9
10
11
12
13
//The alias adapter checks for what event handler methods
//are supported by the loaded jQuery
if ('on' in $) {
//Newer jQuery functions supports the "on" event attachment
//Use the newer event attachment over "bind"
$.fn["evtOn"] = $.fn["on"];
$.fn["evtOff"] = $.fn["off"];
} else {
//Older jQuery version with no "on" function
//Alias bind functions
$.fn["evtOn"] = $.fn["bind"];
$.fn["evtOff"] = $.fn["unbind"];
}

The alias “evtOn” and “evtOff” will be used for attaching and detaching event handlers.

Now the alias can be used like so

Example Adapter Usage
1
2
3
4
5
6
7
$('#my-paragraph').evtOn('click', function () {
alert('Clickity clackity!');
});

$('#my-disabling-button').evtOn('click', function () {
$('#my-paragraph').evtOff('click');
});

The online demo below uses an older version of jQuery (1.6.4) and the adapter alias the “bind” method.

Online Demo