JQuery3.1.1 Source code Interpretation (14) "Event-trigger"

Source: Internet
Author: User
Tags decrypt extend join

Previously, I only knew that only when I clicked on the elements in the browser, I started the Click event, and the other events were the same, requiring human mouse action.

Later, with the continuous deepening of learning, only to know that the original JS can write functions to control the execution of events, this kind of code is meant to write. Remember a long time ago some malicious site, obviously the mouse did not click, but the site was forcibly clicked on a link, probably the way to achieve it. Native Events

In fact, JS's original event has been done quite well, just jQuery to encapsulate it, do better.

For Document.createevent, here is an example of a simple event click:

var fn = function () {
  console.log (' click ');
}

var button = document.getElementById (' #id ');
Button.addeventlistener (' click ', fn);

Click event MouseEvent
var myclick = document.createevent (' MouseEvent ');
Myclick.initmouseevent (' Click ', False, false, NULL);

Execution
button.dispatchevent (Myclick);//' click '

In addition to mouse events, you can customize events:

Arbitrarily customize an event Test.click
button.addeventlistener (' Test.click ', FN);

var testevent = document.createevent (' customevent ');
Customevent can also be initialized as a mouse event, not necessarily a custom event
testevent.initcustomevent (' Test.click ', false, false, NULL);

Button.dispatchevent (testevent); ' Click '

JS native simulation of the event, the use is still very convenient, the above is native.

But JQuery also has its own set of custom event scenarios. Jquery.trigger

Jquery.trigger can be compared with htmlelement.dispatchevent events, which are used to simulate and perform listening events. How to use

It's easier to use. Trigger ():

var $body = $ (document.body);

Bind event
$body first. On (' click ', Function () {
  console.log (' click ');
})

Execute
$body. Trigger (' click ');//' click '

Trigger also supports more parameters and can also customize events:

$body. On (' Click.test ', function (E, data1, data2) {
  console.log (data1 + '-' + data2);
})

$body. Trigger (' click.test ', [' Hello ', ' world ']);
Trigger Source

The source code of trigger is somewhat simple, because still need to use jquery.event to handle:

JQuery.fn.extend ({
  trigger:function (type, data) {
    return This.each (function () {
      JQuery.event.trigger ( Type, data, this)
    ,})
  },
  //Triggerhandler handles the first and does not trigger the default event
  triggerhandler:function (type, data) {
    var elem = this[0];
    if (elem) {
      return JQuery.event.trigger (type, data, Elem, True);}}
);

So the beginning of the trigger event returned to the jquery.event. JQuery.event.trigger

In fact, the trigger and add + handler functions are similar, mostly from the data cache search cache, execute callback function. You need to consider if you want to perform the default event, that is, the fourth argument is true.

Jquery.extend (jquery.event, {///Onleyhandlers) does not consider bubbling event trigger:function (event, data, Elem, onlyhandlers) {V Ar i, cur, tmp, Bubbletype, Ontype, handle, special, Eventpath = [Elem | | document], type = Hasown.call (Eve NT, "type")? Event.type:event, namespaces = Hasown.call (Event, "namespace")?

    Event.namespace.split ("."): []; CUR = tmp = Elem = Elem | |

    Document
    Don ' t does events on text and comment nodes if (elem.nodetype = = = 3 | | elem.nodetype = = 8) {return;
    }//Async does not conflict if (rfocusmorph.test (type + jQuery.event.triggered)) {return;
      } if (Type.indexof (".") >-1) {//namespaced trigger; Create a regexp to match event type in handle ()
      namespaces = Type.split (".");
      Type = Namespaces.shift ();
    Namespaces.sort ();

    } Ontype = Type.indexof (":") < 0 && "on" + type;
      Modified Native Event events = event[Jquery.expando]?
     Event: New Jquery.event (type, typeof event = = = "Object" && event); Determines if only the current trigger event is executed, not bubbling Event.istrigger = onlyhandlers?
    2:3;
    Event.namespace = Namespaces.join (".");
      Event.rnamespace = Event.namespace? New RegExp ("(^|\\.)" + namespaces.join ("\ \ (?:. *\\.|)") + "(\\.|

    $) "): null;
    Clean up the event in case it is being reused event.result = undefined;
    if (!event.target) {event.target = Elem;
      }//Clone any incoming data and prepend the event, creating the handler arg list data = data = null?

    [Event]: Jquery.makearray (data, [Event]); Allow special events to draw outside the lines special = jquery.event.special[Type] | |
    {};
    if (!onlyhandlers && special.trigger && special.trigger.apply (elem, data) = = = False) {return; }//Bubbles the document and stores the bubbling result in the Eventpath array if (!onlyhandlers &&!special.nobubble &&!jquery.i SwiNdow (Elem)) {Bubbletype = Special.delegatetype | | | type;
      if (!rfocusmorph.test (Bubbletype + type)) {cur = Cur.parentnode;
        } for (; cur; cur = cur.parentnode) {eventpath.push (cur);
      TMP = cur; }//Only add window if we got to document (e.g., not plain obj or detached DOM) if (tmp = = = (Elem.ownerdoc ument | |
      Document) {Eventpath.push (Tmp.defaultview | | tmp.parentwindow | | window);
    }}//On demand to execute i = 0;
        while ((cur = eventpath[i++]) &&!event.ispropagationstopped ()) {event.type = i > 1? BubbleType:special.bindType | |

      Type Get callback function from data cache handle = (Datapriv.get (cur, "events") | |
      {}) [Event.type] && datapriv.get (cur, "handle");
      if (handle) {//execute handle.apply (cur, data);
      }//Native handler handle = Ontype && cur[Ontype]; if ( Handle && handle.apply && acceptdata (cur)) {Event.result = handle.apply (cur, data);
        if (Event.result = = = False) {Event.preventdefault ();

    }}} Event.type = type;

      If nobody prevented the default action, do it now if (!onlyhandlers &&!event.isdefaultprevented ()) {
        if ((!special._default | | Special._default.apply (Eventpath.pop (), data) = = = False) && Acceptdata (elem)) {//Call a N
        Ative DOM method on the target with the same name as the event. Don ' t does default actions on window, that's where global variables be (#6170) if (Ontype && jquery.isfu Nction (elem[type]) &&!jquery.iswindow (elem)) {//Don ' t Re-trigger an OnFoo event when we call

          Its FOO () method tmp = elem[Ontype];
          if (TMP) {elem[ontype] = null; }//Prevent re-triggering ofThe same event, since we already bubbled it above jQuery.event.triggered = type;
          elem[type] ();

          jQuery.event.triggered = undefined;
          if (TMP) {elem[Ontype] = tmp;
  }}}} return event.result; },
})
Summary

In JQuery.event.trigger, it is interesting to simulate the bubble mechanism, the general idea is: to put the current elem into an array; find the parent element of the current elem, if fit, push into the array, repeat the first step, or the next step; iterate through the array, from the data cach E, check to see if the type event is bound, and then click Execute.

Bubbling events are the process of bubbling out of the inside out, and the process is not very complicated.

Event events should be about as much content. Reference

Decrypt jquery Event Core-Custom Design (iii)

MDN CreateEvent

Decrypt the jquery event core-simulation event (iv)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.