首页 > 代码库 > 自定义事件

自定义事件

//自定义事件
    function defineEvent(){
        this.handles={};
    }
    defineEvent.prototype={
        constructor:defineEvent,
        addHandler:function(type,handler){
            if(typeof this.handles[type] === ‘undefined‘){
                this.handles[type]=[];
            }
            this.handles[type].push(handler);
        },
        fire:function(event){
            if(!event.target){
                event.target=this;
            }
            if(this.handles[event.type] instanceof Array){
                var hands=this.handles[event.type];
                for(var i=0;i<hands.length;i++){
                    hands[i](event);
                }
            }
        },
        removeHandler:function(type,handler){
            if(this.handles[type] instanceof Array){
                var hands=this.handles[type];
                for(var i=0;i<hands.length;i++){
                    if(hands[i] === handler){
                        break;
                    }
                }
                hands.splice(i,1);
            }
        }
    }
    function fn(event){
        console.log("event:"+event.hit);
    }
    function fn2(event){
        console.log("event:"+event.hit);
    }
    var tar=new defineEvent();
    tar.addHandler("hit",fn);
    tar.addHandler("see",fn2);
    tar.fire({type:"hit",hit:"You Hit Me!"});//event:You Hit Me!
    tar.fire({type:"see",hit:"She See The Sight!"});//event:She See The Sight!
    tar.removeHandler("hit",fn);
    tar.fire({type:"hit",hit:"You Hit Me!"});//该事件已经移除
    tar.fire({type:"see",hit:"She See The Sight!"});//event:She See The Sight!

 

自定义事件