我不知道它是否会“更好”,但以下内容不与 DOM 交互 - 它保留对未附加元素的引用并处理它。尽管无论如何,如果 jQuery 在内部做更多事情,我不会感到惊讶.trigger()
。如果这些事件与 DOM 无关,请远离它 :) 这是一个示例:
var Events = (function () {
"use strict";
var trigger, events, onMethod, triggerMethod;
trigger = $("<div>");
events = {
test1: 1,
test2: 1
};
onMethod = function (eventName, func) {
if (events[eventName]) {
trigger.on(eventName, func);
}
};
triggerMethod = function (eventName) {
trigger.triggerHandler(eventName, Array.prototype.slice.call(arguments, 1));
};
return {
on: onMethod,
trigger: triggerMethod
};
}());
Events.on("test2", function () {
console.log(arguments);
});
Events.trigger("test2", [1, 2, 3], 3);
演示:http: //jsfiddle.net/Kh4HC/
您可能可以删除该events
变量;这只是我定义“允许”的方式。任何由 jQuery 完成的额外事情,以及对 jQuery 的依赖都可以避免,并且可以制作一个小型触发库来完全避开 DOM。或者,使用现有的几个好的库之一也可以。作为一种希望更好地帮助理解这在库内部如何工作的方法,这里有一个例子:
var Events = (function () {
"use strict";
var events, onMethod, triggerMethod, slice;
events = {};
onMethod = function (eventName, func) {
if (!(events[eventName])) {
events[eventName] = [];
}
events[eventName].push(func);
};
triggerMethod = function (eventName) {
var matchedEvent, args, i, j, cur;
matchedEvent = events[eventName];
if (matchedEvent) {
args = slice(arguments, 1);
for (i = 0, j = matchedEvent.length; i < j; i++) {
cur = matchedEvent[i];
cur.apply(null, args);
}
}
};
slice = function (arr, start, howMany) {
var stop, newArr, i, j, cur;
start = +start || 0;
howMany = +howMany || Infinity;
stop = Math.min(start + howMany, arr.length);
newArr = [];
for (i = start, j = stop; i < j; i++) {
cur = arr[i];
newArr.push(cur);
}
return newArr;
};
return {
on: onMethod,
trigger: triggerMethod
};
}());
Events.on("ahh", function () {
console.log("ahh", arguments);
});
Events.trigger("ahh", [1, 2, 3], 3);
Events.trigger("ahh", {a: "b"}, true);
演示:http: //jsfiddle.net/Zv2W8/1/