Home > Article > Web Front-end > Custom events in javascript
Custom event: The user can specify the event type, which is actually a string, and then specify an event processing function for this type of event. Multiple event processing functions can be registered (managed with arrays). When called, from multiple Find it in the event handling function and then call it.
function EventTarget(){ this.handlers={}; } EventTarget.prototype={ constructor:EventTarget, addHandler:function(type,handler){ if(typeof this.handlers[type]=='undefined'){ this.handlers[type]=new Array(); } this.handlers[type].push(handler); }, 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(handler[i]==handler){ handlers.splice(i,1); break; } } } }, trigger: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); } } } }
The addHandler method is used to add event handlers, and the removeHandler method is used to remove event handlers. All event handlers are stored and managed uniformly in the attribute handlers. Call the trigger method to trigger an event. This method receives an object containing at least a type attribute as a parameter. When triggered, it will search for the event handler corresponding to the type in the handlers attribute. Write a piece of code to test it.
function onClose(event){ alert('message:'+event.message); } var target=new EventTarget(); target.addHandler('close',onClose); //浏览器不能帮我们创建事件对象了,自己创建一个,自定义事件对象的属性 var event={ type:'close', message:'Page Cover closed!' }; target.trigger(event);