我只是建议一个回调对象数组,您可以将它们封装在它自己的对象中。该对象具有添加、删除和执行的方法。添加,按优先级顺序添加给定的回调。Remove 找到回调并将其删除。Execute 按优先级顺序调用每个回调,但如果有任何回调返回,则停止进一步执行回调false
。
按优先级顺序遍历回调很简单(您只需从数组的开头到结尾),因为回调在数组中保持排序顺序。
function sortedCallbacks() {
this.list = [];
}
sortedCallbacks.prototype = {
// add callback to the list
add: function(fn, priority, data) {
var list = this.list;
var callbackObj = {fn: fn, priority: priority, data: data};
for (var i = 0; i < list.length; i++) {
// if our new priority is greater, then insert it here
if (priority > list[i].priority) {
list.splice(i, 0, callbackObj);
return;
}
}
// if the list was either empty or no priorities in the list were less than
// the new priority, then just add this onto the end of the list
list.push(callbackObj);
},
// remove callback from the list
remove: function(fn, priority) {
var list = this.list;
for (var i = 0; i < list.length; i++) {
if (list[i].fn === fn && list[i].priority === priority) {
list.splice(i, 1);
return;
}
}
},
// change priority or data or both
change: function(fn, oldPriority, newPriority, data) {
this.remove(fn, oldPriority);
this.add(fn, newPriority, data);
}
// execute callbacks in order
execute: function(/* args for callback passed here */) {
// execute in priority order
var list = this.list, retVal, args;
for (var i = 0; i < list.length; i++) {
args = [].slice.call(arguments, 0);
// add the data for this callback to any arguments that were passed to execute
args.unshift(list[i].data);
retVal = list[i].fn.apply(this, args);
// if callback returns false, then stop further callback execution
if (retVal === false) {
return;
}
}
}
};
示例用法:
// create callbacks object and add some callbacks to it
var callbacks = new sortedCallbacks();
callbacks.add(fn1, 4, "whatever");
callbacks.add(fn2, 9, "hello");
callbacks.add(fn8, -1, "nothing");
// execute the callbacks and pass them each a value
callbacks.execute(elem.value)