1 window.meng = window.meng || {}; 2 (function () { 3 4 var items = []; 5 6 meng.queue = { 7 /** 8 * 9 * @param {Function} item 10 */ 11 addItem: function (item) { 12 items.push(item); 13 }, 14 /** 15 * 16 * @param {Function} item 17 */ 18 removeItem: function (item) { 19 if (item){ 20 var index = items.indexOf(item); 21 if (index != -1) { 22 items.splice(index, 1); 23 } 24 }else { 25 items.pop(); 26 } 27 28 }, 29 removeAllItem: function (item) { 30 while (true) { 31 var index = items.indexOf(item); 32 if (index != -1) { 33 items.splice(index, 1); 34 } else { 35 return false; 36 } 37 } 38 39 }, 40 removeAll: function () { 41 items.splice(0, items.length); 42 }, 43 runItem: function () { 44 for (var i = 0; i < items.length; i++) { 45 items[i](); 46 } 47 } 48 } 49 50 })();
代码测试
1 (function () { 2 3 function logA() { 4 console.log("A"); 5 } 6 7 function logB() { 8 console.log("B"); 9 } 10 11 function logC() { 12 console.log("C"); 13 } 14 15 function queue() { 16 meng.queue.addItem(logA); 17 meng.queue.addItem(logC); 18 meng.queue.addItem(logC); 19 meng.queue.removeAllItem(logB); 20 meng.queue.removeItem(logA); 21 meng.queue.removeAll(); 22 meng.queue.removeItem(); 23 24 meng.queue.runItem(); 25 } 26 27 function init() { 28 console.log("排序之前"); 29 logA(); 30 logB(); 31 logC(); 32 console.log("排序之后"); 33 34 queue(); 35 } 36 37 init(); 38 })();