Home >Web Front-end >JS Tutorial >Custom events in javascript

Custom events in javascript

高洛峰
高洛峰Original
2016-11-16 11:22:351556browse

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(&#39;message:&#39;+event.message);
        }
 
        var target=new EventTarget();
        target.addHandler(&#39;close&#39;,onClose);
 
        //浏览器不能帮我们创建事件对象了,自己创建一个,自定义事件对象的属性
        var event={
            type:&#39;close&#39;,
            message:&#39;Page Cover closed!&#39;
        };
 
        target.trigger(event);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn