Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - i want to know how jquery' delegate or on(for delegate) works

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
}

i had wrote this before:

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;
      }
    }

}

someone know how jquery's work method on 'delegate' or 'on' for delegate?please show me the code simply description for 'delegate'..thanks alot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have a look at the jQuery docs for on(), they explain the concept very well.

Also, you can have a look at the source code!

The lessons learned:

  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...