我想知道 jquery 的委托或 on(for delegate) 是如何工作的 [英] i want to know how jquery' delegate or on(for delegate) works

查看:20
本文介绍了我想知道 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,从委托的处理程序开始.
  • delegate is just a wrapper for on with different parameter order
  • on does just some parameter normalisation and handles one, but delegates then to jQuery.event.add( this, types, fn, data, selector );
  • event.add does do a lot of validation, handles multiple types and special cases, pushes the arguments on $.data("events") and calls elem.addEventListener(type, jQuery.event.dispatch, false)
  • event.dispatch then queries the handles from $.data("events") again and builds a jqEvent from the native event. Then it begins searching for delegated events - the code for that is quite straightforward - and pushes them on the handlerQueue, after that the normal handlers which are attached directly on the element. In the end, it just runs the handlerQueue, starting with the delegated handlers.

这篇关于我想知道 jquery 的委托或 on(for delegate) 是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆