Updating plugins to use the new jQuery.on event binding method in a backwards compatible way
I’m going through all my written/half-written/never really gonna get written properly probably jQuery plugins to ready them for the new jQuery plugins site. While I’m at it I’m updating as many event handlers as I can to use the new $.on method (as other event binding methods are likely to be deprecated in future).
This presents a problem as I would like to achieve backwards compatibility too. A simple solution for the bind method is:
var binder = $.fn.on ? "on": "bind";
$(this)[binder]("click", handler);
But I’ve also put together this more generic solution (this is completely untested, but something like this should work)
if(!$.fn.on) {
$.fn.on = function(events, selector, data, handler) {
if(typeof selector == "function") {
return $.fn.bind.call(this, selector);
} else if(typeof selector == "object"){
return $.fn.bind.call(this, selector, data)
} else {
return $.fn.delegate.call(this, selector, data, handler)
}
}
$.fn.off = function(events, selector, handler) {
if(typeof selector == "function") {
return $.fn.unbind.call(this, selector);
} else {
return $.fn.undelegate.call(this, selector, handler)
}
}
}
Related posts:
- Two small but useful javascript factsPassing parameters into setTimeout callbacks setTimeout (and setInterval too perhaps?)...