js自定義事件的簡單實現

2021-08-27 12:28:51 字數 1330 閱讀 7566

在寫這段**之後,本人使用過jquery這個庫,一直對jquery的自定義事件有疑惑,就看了看jquery的原始碼,廓然開朗。

jquery**實現和觸發自定義實現如下: 

jquery的定義方式:

$(dom).bind('data-change',function())

jquery使用方式 :

$(dom).trigger('init-change',[data]);

但內部機制是怎麼觸發這個事件的呢?原來jquery通過的是快取這些自定義事件,我就自己實現了一把,下面是我的**:

var dojo = function

(selecter,context)

dojo.prototype.event ={};

dojo.prototype.init = function

(selecter,context)

dojo.prototype.getdom = function

(selecter)

dojo.prototype.addevent = function(eventname,fn)

this

.event[eventname].push( fn );}//

dojo工具類

dojo.util ={};

dojo.util.isfunction = function

(fn)

dojo.util.toarray = function

(args)

//簡單實現事件的繫結

dojo.prototype.click = function

(fn) ,

false

); }

}}dojo.prototype.trigger = function

(eventname,data)

for(len = this.event[eventname].length;i)

return

this;}

dojo.prototype.init.prototype =dojo.prototype;

var dom = new dojo('dom');

//為建立的dom物件增加自定義函式

//這裡面就增加了兩個一樣的事件

dom.addevent("data-change",function

());

dom.addevent("data-change",function

());

//click的時候觸發事件

dom.click(function

(e));

js自定義事件

使用event let myevent new event event name 為了能夠傳遞引數,使用customevent let mycusevent new customevent event name customenent的另種寫法 首先建立自定義事件物件 let event docum...

js自定義事件

customevent event new customevent typearg,1.用法 定義事件 var event new customevent student 監聽事件 domelement.addevent student function e 觸發事件,同乙個監聽的dom元素,dis...

js自定義事件

自定義事件的本質,建立乙個物件,然後把事件的名字作為物件的乙個屬性,然後value是乙個,把此事件的所以 都push進去。寫乙個很基本的,沒有把物件暴露出去的js的自定義事件。1 varevent function 3var addevent function type,cb 7return obj...