
jQuery event priority
By:
Dramiel on
Dec 7th, 2011 | syntax:
JavaScript | size: 1.54 KB | hits: 90 | expires: Never
// extend jquery to allow event priority
(function ($) {
var _on = $.fn.on;
function enumTypes(types, fn) {
types = jQuery.trim(types).split(" ");
for (i = 0; i < types.length; i++) {
var type = types[i];
fn.call(this, type);
}
}
function sortEvents(types) {
enumTypes.call(this, types, function (type) {
this.each(function () {
var events = $.data(this, "events")[type.split(".")[0]];
var handlers = events.slice(events.delegateCount);
handlers.sort(function (a, b) {
var ap = typeof (a.priority) === "number" ? a.priority : 0;
var bp = typeof (b.priority) === "number" ? b.priority : 0;
if (ap > bp)
return -1;
if (ap < bp)
return 1;
return 0;
});
for (var i = 0; i < handlers.length; i++) {
events[events.delegateCount + i] = handlers[i];
}
});
});
}
$.fn.on = function (types, selector, data, fn) {
if (typeof types === "object") {
return _on.apply(this, arguments);
}
var result;
if (typeof types === "string" && typeof selector === "number" && typeof data === "function") {
var priority = selector;
fn = data;
result = _on.call(this, types, fn);
enumTypes.call(this, types, function (type) {
this.each(function () {
var events = $.data(this, "events")[type.split('.')[0]];
events[events.length - 1].priority = priority;
});
});
} else
result = _on.apply(this, arguments);
sortEvents.call(this, types);
return result;
}
} (jQuery));