i want to know how jquery' delegate or on(for delegate) works
delegates, javascript, jquery
Solution
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.
Problem
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.