Javascript自訂事件

來源:互聯網
上載者:User

Javascript自訂事件
事件是與DOM互動的最常見的方式,但它也可以用於非DOM代碼中--通過實現自訂事件.實現自訂事件的原理是建立一個管理事件的對象.第一步:建立事件對象function EventTarget(){    this.handlers = {};//儲存結構:{事件名1:[func1,func2……],事件名2:[func1,func2……]……}} 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++){                //將event傳遞給事件處理常式,event.target代表對象本身,                event.type代表事件名,你可以根據情況為添加event屬性                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);    }} };第二步:事件調用var eventObj=new (); //執行個體化一個EventTarget類型var handler=function(){    alert('event');};  //事件處理常式eventObj.addHandler('alert',handler); //為eventObj對象添加一個事件處理常式`handler`event.fire({type:'alert'});  //觸發eventObj對象中的事件處理常式`handler`event.removeHandler('alert',handler);  //刪除eventObj對象中的事件處理常式`handler`擴充:(事件繼承)我們可以讓其他類型繼承EventTarget的屬性和方法定義繼承方法//原型式繼承var object=function(o){//F起到中轉作用,避免參入多餘屬性    function F(){}    F.prototype=o;    return new F();};  //subType繼承superType的原型對象var inheritPrototype=function(subType,superType){     var prototype=object(superType.prototype);    prototype.constructor=subType;    subType.prototype=prototype; }//實現繼承並擴充屬性function Person(name,age){        EventTarget.call(this);//繼承EventTarget的屬性    this.name = name;    this.age = age;} inheritPrototype(Person,EventTarget);//繼承EventTarget的方法 Person.prototype.say=function(message){    this.fire({type:'message',message:message}); //觸發事件};//調用//事件處理常式var handMessage=function(event){     alert(event.target.name + "says:" + event.message); }; var person=new Person('yhlf',29);person.addHandler('message',handMessage);person.say('Hi there'); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.