jquery事件綁定解綁機(jī)制源碼解析
引子
為什么Jquery能實(shí)現(xiàn)不傳回調(diào)函數(shù)也能解綁事件?如下:
$("p").on("click",function(){
alert("The paragraph was clicked.");
});
$("#box1").off("click");
事件綁定解綁機(jī)制
調(diào)用on函數(shù)的時(shí)候,將生成一份事件數(shù)據(jù),結(jié)構(gòu)如下:
{
type: type,
origType: origType,
data: data,
handler: handler,
guid: guid,
selector: selector,
needsContext: needsContext,
namespace: namespace
}
并將該數(shù)據(jù)加入到元素的緩存中。jquery中每個(gè)元素都可以有一個(gè)緩存(只有有需要的時(shí)候才生成),其實(shí)就是該元素的一個(gè)屬性。jquery為每個(gè)元素的每種事件都建立一個(gè)隊(duì)列,用來(lái)保存事件處理函數(shù),所以可以對(duì)一個(gè)元素添加多個(gè)事件處理函數(shù)。緩存的結(jié)構(gòu)如下:
"div#box":{ //元素
"Jquery623873":{ //元素的緩存
"events":{
"click":[
{ //元素click事件的事件數(shù)據(jù)
type: type,
origType: origType,
data: data,
handler: handler,
guid: guid,
selector: selector,
needsContext: needsContext,
namespace: namespace
}
],
"mousemove":[
{
type: type,
origType: origType,
data: data,
handler: handler,
guid: guid,
selector: selector,
needsContext: needsContext,
namespace: namespace
}
]
}
}
}
當(dāng)要解綁事件的時(shí)候,如果沒(méi)指定fn參數(shù),jquery就會(huì)從該元素的緩存里拿到要解綁的事件的處理函數(shù)隊(duì)列,從里面拿出fn參數(shù),然后調(diào)用removeEventListener進(jìn)行解綁。
源代碼
代碼注釋可能不太清楚,可以復(fù)制出來(lái)看
jquery原型中的on,one,off方法:
事件綁定從這里開(kāi)始
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
//此處省略處理參數(shù)的代碼
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
}
} );
獨(dú)立出來(lái)供one和on調(diào)用的on函數(shù):
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
//此處省略處理參數(shù)的代碼
//是否是通過(guò)one綁定,是的話使用一個(gè)函數(shù)代理當(dāng)前事件回調(diào)函數(shù),代理函數(shù)只執(zhí)行一次
//這里使用到了代理模式
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
/************************************************
*** jquery將所有選擇到的元素到放到一個(gè)數(shù)組里,然后
*** 對(duì)每個(gè)元素到使用event對(duì)象的add方法綁定事件
*************************************************/
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
處理參數(shù)的代碼也可以看一下,實(shí)現(xiàn)on("click",function(){})這樣調(diào)用 on:function(types, selector, data, fn)也不會(huì)出錯(cuò)。其實(shí)就是內(nèi)部判斷,如果data, fn參數(shù)為空的時(shí)候,把selector賦給fn
event對(duì)象是事件綁定的一個(gè)關(guān)鍵對(duì)象:
這里處理把事件綁定到元素和把事件信息添加到元素緩存的工作:
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.get( elem ); //這句將檢查elem是否被緩存,如果沒(méi)有將會(huì)創(chuàng)建一個(gè)緩存添加到elem元素上。形式諸如:elem["jQuery310057655476080253721"] = {}
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
//用戶可以傳入一個(gè)自定義數(shù)據(jù)對(duì)象來(lái)代替事件回調(diào)函數(shù),將事件回調(diào)函數(shù)放在這個(gè)數(shù)據(jù)對(duì)象的handler屬性里
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
//每個(gè)事件回調(diào)函數(shù)都會(huì)生成一個(gè)唯一的id,以后find/remove的時(shí)候會(huì)用到
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// 如果元素第一次綁定事件,則初始化元素的事件數(shù)據(jù)結(jié)構(gòu)和主回調(diào)函數(shù)(main)
//說(shuō)明:每個(gè)元素有一個(gè)主回調(diào)函數(shù),作為綁定多個(gè)事件到該元素時(shí)的回調(diào)的入口
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
//這里就是初始化主回調(diào)函數(shù)的代碼
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// 處理事件綁定,考慮到可能會(huì)通過(guò)空格分隔傳入多個(gè)事件,這里要進(jìn)行多事件處理
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// 事件回調(diào)函數(shù)的數(shù)據(jù)對(duì)象
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// 加入第一次綁定該類(lèi)事件,會(huì)初始化一個(gè)數(shù)組作為事件回調(diào)函數(shù)隊(duì)列,每個(gè)元素的每一種事件有一個(gè)隊(duì)列
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// 加入到事件回調(diào)函數(shù)隊(duì)列
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
// 用來(lái)追蹤哪些事件從未被使用,用以優(yōu)化
jQuery.event.global[ type ] = true;
}
}
};
千萬(wàn)注意,對(duì)象和數(shù)組傳的是引用!比如將事件數(shù)據(jù)保存到緩存的代碼:
handlers = events[ type ] = [];
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
handlers的改變,events[ type ]會(huì)同時(shí)改變。
dataPriv就是管理緩存的對(duì)象:
其工作就是給元素創(chuàng)建一個(gè)屬性,這個(gè)屬性是一個(gè)對(duì)象,然后把與這個(gè)元素相關(guān)的信息放到這個(gè)對(duì)象里面,緩存起來(lái)。這樣需要使用到這個(gè)對(duì)象的信息時(shí),只要知道這個(gè)對(duì)象就可以拿到:
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
//刪除部分沒(méi)用到代碼
Data.prototype = {
cache: function( owner ) {
// 取出緩存,可見(jiàn)緩存就是目標(biāo)對(duì)象的一個(gè)屬性
var value = owner[ this.expando ];
// 如果對(duì)象還沒(méi)有緩存,則創(chuàng)建一個(gè)
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
// Always use camelCase key (gh-2257) 駝峰命名
owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
},
remove: function( owner, key ) {
var i,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key !== undefined ) {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map( jQuery.camelCase );
} else {
key = jQuery.camelCase( key );
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ?
[ key ] :
( key.match( rnotwhite ) || [] );
}
i = key.length;
while ( i-- ) {
delete cache[ key[ i ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- jQuery?事件綁定及取消?bind?live?delegate?on?one區(qū)別解析
- jquery事件綁定方法介紹
- jQuery事件綁定和解綁、事件冒泡與阻止事件冒泡及彈出應(yīng)用示例
- jQuery實(shí)現(xiàn)的事件綁定功能基本示例
- jQuery的三種bind/One/Live/On事件綁定使用方法
- jQuery 全選 全不選 事件綁定的實(shí)現(xiàn)代碼
- jQuery事件綁定方法學(xué)習(xí)總結(jié)(推薦)
- jquery移除了live()、die(),新版事件綁定on()、off()的方法
- 關(guān)于Jquery中的事件綁定總結(jié)
- jQuery事件綁定用法詳解
- 深入理解jQuery事件綁定
- jQuery事件綁定on()與彈窗實(shí)現(xiàn)代碼
- jQuery事件綁定用法詳解(附bind和live的區(qū)別)
- jQuery實(shí)現(xiàn)按鈕只點(diǎn)擊一次后就取消點(diǎn)擊事件綁定的方法
- JQuery中DOM事件綁定用法詳解
- jQuery事件綁定on()、bind()與delegate() 方法詳解
- jQuery事件綁定與解除綁定實(shí)現(xiàn)方法
- jquery中click等事件綁定及移除的幾種方法小結(jié)
相關(guān)文章
Jquery AJAX 用于計(jì)算點(diǎn)擊率(統(tǒng)計(jì))
Jquery AJAX實(shí)現(xiàn)頁(yè)面的統(tǒng)計(jì)代碼,后臺(tái)用的是php,這篇文章主要是學(xué)習(xí)jquery下ajax的簡(jiǎn)單實(shí)現(xiàn)。2010-06-06
jQuery 獲取select選中值及清除選中狀態(tài)
這篇文章主要介紹了jQuery 獲取select選中值及清除選中狀態(tài)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-12-12
在css加載完畢后自動(dòng)判斷頁(yè)面是否加入css或js文件
使用jquery ui中的dialog()來(lái)顯示消息框,為了使方法方便調(diào)用,便加入了自動(dòng)判斷頁(yè)面是否加入了ui.js和ui.css,具體實(shí)現(xiàn)代碼如下2014-09-09
Jquery Easyui分割按鈕組件SplitButton使用詳解(17)
這篇文章主要為大家詳細(xì)介紹了Jquery Easyui分割按鈕組件SplitButton的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
jQuery Validate表單驗(yàn)證入門(mén)學(xué)習(xí)
這篇文章主要介紹了jQuery Validate表單驗(yàn)證入門(mén)知識(shí),該插件捆綁了一套有用的驗(yàn)證方法,包括 URL 和電子郵件驗(yàn)證,同時(shí)提供了一個(gè)用來(lái)編寫(xiě)用戶自定義方法的 API,感興趣的小伙伴們可以參考一下2015-12-12
jquery實(shí)現(xiàn)非疊加式的搜索框提示效果
用JQUERY疊加兩個(gè)INPUT框來(lái)實(shí)現(xiàn)登陸中需要輸入的用戶名、密碼來(lái)實(shí)現(xiàn)提示與用戶的輸出,使用jquery在一個(gè)INPUT框中即可實(shí)現(xiàn)2014-01-01
jQuery實(shí)現(xiàn)拼圖小游戲(實(shí)例講解)
下面小編就為大家?guī)?lái)一篇jQuery實(shí)現(xiàn)拼圖小游戲(實(shí)例講解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07
ASP.NET jQuery 實(shí)例3 (在TextBox里面阻止復(fù)制、剪切和粘貼事件)
在這講里,讓我們看下如何在ASP.NET Textbox里禁止復(fù)制、剪切和粘貼行為2012-01-01

