自定义事件
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title> 自定义事件 </title> </head> <body> </body> </html> <script> 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); } } } function fn_message(event){ alert(event.message); } var target = new EventTarget(); target.addHandler('message',fn_message); target.fire({type:'message',message:'I love javascript'}); target.removeHandler('message',fn_message); target.fire({type:'message',message:'I love javascript'}); </script>