我想知道 jquery 的委托或 on(for delegate) 是如何工作的
有时我使用 on 来委托事件,
sometimes i use on to delegate event ,
dom.addEventListener("click",function(e){
e.target for hander.
}
instead:
dom.on("click",'a',function(){
$(this).handler..
}
所以,我想我可以这样写代码:
so,i guess i can write codes in this way :
function delegate(dom,event,selector,handler){
target = event.target;
while selector.dom.not_match event.target
target = target.parentNode
recheck until match the selector and do handler;
end
}
我以前写过这个:
function delegate(dom,event,selector,handler){
dom.addEvent event function(){
target_arr = dom.find(selector);
if(event.target in_array target_arr){
do handler
}else{
target = target.parentNode until dom.
recheck in target_arr;
}
}
}
有人知道 jquery 在 'delegate' 或 'on' 上为 delegate 的工作方法吗?请给我看一下'delegate' 的代码简单描述......非常感谢.
someone know how jquery's work method on 'delegate' or 'on' for delegate?please show me the code simply description for 'delegate'..thanks alot.
推荐答案
看看 on() 的 jQuery 文档,他们很好地解释了这个概念.
Have a look at the jQuery docs for on(), they explain the concept very well.
另外,您可以查看源代码!
经验教训:
委托只是on的包装器,具有不同的参数顺序on只做一些参数规范化并处理one,然后委托给jQuery.event.add( this, types, fn, data, selector );event.add确实做了很多验证,处理多种类型和特殊情况,将参数推送到$.data("events")并调用elem.addEventListener(type, jQuery.event.调度,假)event.dispatch然后再次从$.data("events")查询句柄并构建一个jqEvent来自本机事件.然后它开始搜索委托事件 - 代码 非常简单 - 并将它们推送到handlerQueue上,然后是直接附加在元素上的普通处理程序.最后,它只是 运行handlerQueue,从委托的处理程序开始.
delegateis just a wrapper foronwith different parameter orderondoes just some parameter normalisation and handlesone, but delegates then tojQuery.event.add( this, types, fn, data, selector );event.adddoes do a lot of validation, handles multiple types and special cases, pushes the arguments on$.data("events")and callselem.addEventListener(type, jQuery.event.dispatch, false)event.dispatchthen queries the handles from$.data("events")again and builds ajqEventfrom the native event. Then it begins searching for delegated events - the code for that is quite straightforward - and pushes them on thehandlerQueue, after that the normal handlers which are attached directly on the element. In the end, it just runs thehandlerQueue, starting with the delegated handlers.
相关文章