浅谈jQuery事件绑定原理
jq里面有一个data的方法,给dom元素绑定相关的数据的。当给dom用jq的方法绑定了事件,会生成对应的时间列表
可以看下面的例子(请在firefox中查看因为firefox中对象支持toSource())
<!DOCTYPEhtml> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/> <title></title> </head> <body> <divid="test"></div> <scripttype="text/javascript"src="http://common.cnblogs.com/script/jquery.js"></script> <scripttype="text/javascript"> window.onload=function(){ alert($.data($('#test')[0],'events'));//null alert($.data($('#test')[0],'handle'));//null $('#test') .bind('click',function(){ alert(1) }) .bind('mouseover',function(){ alert(2) }) .bind('click',function(){ alert(3) }) .bind('click',function(){ alert(4) }) alert($.data($('#test')[0],'events').toSource());//时间列表 alert($.data($('#test')[0],'handle').toSource());//执行的函数 } </script> </body> </html>
data是给元素绑定数据的
数据源是cache对象
当元素绑定数据的时候会给元素添加一个属性 jQueryxxx xxx为执行jq的时间戳
这里要说明一下,有一个uuid他是累加的
jQueryxxx的值就是这个uuid
cache的key就是这个uuid
value就是要存的数据
data对于事件的绑定是很重要的................................
functionnow(){ return+newDate; }; varwin =this, expando="jQuery"+now(), uuid =0, cache ={}; win.data=function(elem,name,data){ varid=elem[expando]; if(!id) id=elem[expando]=++uuid; if(name&&!cache[id]) cache[id]={}; if(data!==undefined) cache[id][name]=data; returnname ?cache[id][name] :id; } win.removeData=function(elem,name){ varid=elem[expando]; if(name){ if(cache[id]){ deletecache[id][name]; name=""; for(nameincache[id]) break; if(!name) removeData(elem); } }else{ try{ deleteelem[expando]; }catch(e){ if(elem.removeAttribute) elem.removeAttribute(expando); } deletecache[id]; } }
win.each=function(object,callback,args){ varname,i=0,length=object.length; if(args){ if(length===undefined){ for(nameinobject) if(callback.apply(object[name],args)===false) break; }else for(;i<length;) if(callback.apply(object[i++],args)===false) break; }else{ if(length===undefined){ for(nameinobject) if(callback.call(object[name],name,object[name])===false) break; }else for(varvalue=object[0]; i<length&&callback.call(value,i,value)!==false;value=object[++i]){} } returnobject; }