JavaScript 一個最簡單的事件模型,需要有事件綁定與觸發,還有事件刪除。
var eventModel = { list: {}, bind: function () { var args = [].slice.call(arguments), type = args[0], handlers = args.slice(1); if (typeof type === 'string' && handlers.length > 0) { for (var i = 0; i < handlers.length; i++) { if (typeof handlers[i] === 'function') { if (!this.list[type]) { this.list[type] = []; } this.list[type].push(handlers[i]); } } } }, unbind: function () { var type = arguments[0], handlers = Array.prototype.slice.call(arguments, 1); if (typeof type === 'string') { if (handlers.length === 0) { this.list[type] = []; } else { for (var i = 0; i < handlers.length; i++) { if (typeof handlers[i] === 'function' && handlers[i] === this.list[type][i]) { this.list[type].splice(i, 1); } } } } }, trigger: function () { var arguments = [].slice.call(arguments), type = arguments[0], args = arguments[1] instanceof Array && !arguments[2] ? arguments[1] : arguments.slice(1), handlers = this.list[type]; for (var i = 0; i < handlers.length; i++) { handlers[i].apply(this, args.splice(0, handlers[i].length)); } }};
其中主要實現了bind(綁定事件)、unbind(刪除事件)與 trigger (觸發事件)。對同一事件名稱,可以綁定多個事件處理函數;并按照綁定的順序依次觸發。
args.splice(0, handlers[i].length) 觸發時的傳參
事件綁定與觸發:
eventModel.bind('myevent1', function (a) { console.log(a); // 1}, function(b) { console.log(b); // 2}, function(c, d) { console.log(c + ' + ' + d); // a + b});eventModel.bind('myevent1', function (e) { console.log(e); // 50});eventModel.trigger('myevent1', 1,2,'a','b', 50);
事件刪除:
<button id="bind">bind</button><button id="unbind">unbind</button>
var fnX = function () { console.log('fnX');}var fnY = function () { console.log('fnY');}eventModel.bind('myevent2', fnX, fnY);document.getElementById('unbind').onclick = function () { eventModel.unbind('myevent2', fnX); //刪除 fnX 后,只剩下 fnY};document.getElementById('bind').onclick = function () { eventModel.trigger('myevent2'); //輸出 fnX fnY //在點擊unbind后,只輸出 fnY};
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答