自定义事件
1 //自定义事件 2 function EventTarget() { 3 this.handlers = {}; 4 } 5 EventTarget.prototype = { 6 constructor: EventTarget, 7 //注册 8 addHandler: function(type, handler) { 9 if (typeof this.handlers[type] == "undefined") { 10 this.handlers[type] = []; 11 } 12 this.handlers[type].push(handler); 13 }, 14 //触发 15 fire: function(event) { 16 if (!event.target) { 17 event.target = this; 18 } 19 if (this.handlers[event.type] instanceof Array) { 20 var handlers = this.handlers[event.type]; 21 for (var i = 0, len = handlers.length; i < len; i++) { 22 handlers[i](event); 23 } 24 } 25 }, 26 //注销 27 removeHandler: function(type, handler) { 28 if (this.handlers[type] instanceof Array) { 29 var handlers = this.handlers[type]; 30 for (var i = 0, len = handlers.length; i < len; i++) { 31 if (handlers[i] === handler) { 32 break; 33 } 34 } 35 handlers.splice(i, 1); 36 } 37 } 38 };
1 //使用方法 2 function handleMessage(event) { 3 alert("Message received: " + event.message); 4 } 5 //创建一个新对象 6 var target = new EventTarget(); 7 //添加一个事件处理程序 8 target.addHandler("message", handleMessage); 9 //触发事件 10 target.fire({ 11 type: "message", 12 message: "Hello world!" 13 }); 14 //删除事件处理程序 15 target.removeHandler("message", handleMessage); 16 //再次,应没有处理程序 17 target.fire({ 18 type: "message", 19 message: "Hello world!" 20 });