观察者模式和js自定义事件
生活随笔
收集整理的這篇文章主要介紹了
观察者模式和js自定义事件
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
事件是一種叫做觀察者的設計模式,觀察者模式由兩類對象組成:主體和觀察者。主體負責發(fā)布事件,同時觀察者通過訂閱這些事件來觀察該主體。拿DOM來說,DOM就是主體,事件處理代碼便是觀察者。
下面是一個自定義事件,
function EventTarget() {this.handlers = {}; } EventTarget.prototype = {constructor: EventTarget,addHandler: function (type, handler) {if (typeof this.handlers[type] == 'undefined') {this.handlers[type] = [];}this.handlers[type].push(handler);},fire: function (event) {if (!event.target) {event.target = this;}if (this.handlers[event.type] instanceof Array) {var handlers = this.handlers[event.type];for (var i = 0, len = handlers.length; i < len; i++) {handlers[i](event);}}},removeHandler: function (type, handler) {if (this.handlers[type] instanceof Array) {var handlers = this.handlers[type];for (var i = 0, len = handlers.length; i < len; i++) {if (handlers[i] === handler) {break;}}handlers.splice(i, 1);}} }自定義事件的調(diào)用,addHandler() 添加事件,fire() 執(zhí)行事件,removeHandler() 刪除綁定的事件。
function handleMessage1(event) {console.log("111--", event.message); } function handleMessage2(event) {console.log("222--", event.message); } var target = new EventTarget(); // 添加事件 target.addHandler('message', handleMessage1); target.addHandler('message', handleMessage2); // 執(zhí)行事件 target.fire({type: 'message',message: 'hello!' })// 刪除事件 target.removeHandler('message', handleMessage1); // 執(zhí)行事件 target.fire({type: 'message',message: 'holy' })
總結(jié)
以上是生活随笔為你收集整理的观察者模式和js自定义事件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】全方面解读Python的
- 下一篇: push_back还是emplace_b