Read jquery 14 (the core method of triggering event) _jquery

Source: Internet
Author: User
In the evolution of the event module I used dispatchevent (standard) and fireevent (IE) to actively trigger events. As follows
Copy Code code as follows:

...
Dispatch = The consortium?
Function (el, type) {
try{
var evt = document.createevent (' Event ');
Evt.initevent (type,true,true);
El.dispatchevent (EVT);
}catch (e) {alert (e)};
} :
Function (el, type) {
try{
El.fireevent (' on ' +type);
}catch (e) {alert (e)}
};
...

jquery does not use the Dispatchevent/fireevent method at all. It uses a different mechanism.
The core method of the JQuery trigger event is JQuery.event.trigger. There are two triggering event methods available to client programmers:. Trigger/.triggerhandler

The occurrence of an event in some elements can result in two kinds of actions, one is the default behavior, the other is event handler. such as Link a
<a href= "http://mail.sina.com.cn" onclick= "alert (1);" > Sina Email </a>
After clicking, Pop 1 (event handler), click OK jump (default behavior) to mail.sina.com.cn. Therefore, the design of the function that triggers the event takes into account both of these situations.
jquery uses. Trigger and. Triggerhandler distinguish between these two situations:
. Trigger Execute event hanlder/perform bubbling/perform default behavior
. Triggerhandler execution Event handler/does not bubble/do not perform default behavior
Copy Code code as follows:

. Trigger/.triggerhandler's source code is as follows
Trigger:function (type, data) {
Return This.each (function () {
JQuery.event.trigger (type, data, this);
});
},
Triggerhandler:function (type, data) {
if (This[0]) {
Return JQuery.event.trigger (type, data, This[0], true);
}
},

As you can see, both call JQuery.event.trigger. One does not pass true when called, and one passes. A triggerhander that passes true means that only the event handler is executed.
There is also a distinction to be noted:. Trigger is an operation on a collection of jquery objects, and. Triggerhandler only manipulate the first element of the jquery object. As follows
Copy Code code as follows:

<p>p1</p>
<p>p1</p>
<p>p1</p>
<script>
$ (' P '). Click (function () {alert (1)});
$ (' P '). Trigger (' click '); Play 3 times, that is, three P's click is triggered
$ (' P '). Triggerhandler (' click '); Only 1 times, that only triggers the first p click
</script>

Okay, it's time to post the JQuery.event.trigger code.
Copy Code code as follows:

Trigger:function (event, data, Elem, onlyhandlers) {
Event object or event type
var type = Event.type | | Event
namespaces = [],
Exclusive
......
}

This is the definition of JQuery.event.trigger, which omits most of it. The following list
Copy Code code as follows:

if (Type.indexof ("!") >= 0) {
Exclusive events trigger only for the exact event (no namespaces)
Type = Type.slice (0,-1);
Exclusive = TRUE;
}

This paragraph is to deal with. Trigger (' click! ') , which triggers an event that is not a namespace. Variable exclusive is used within jQuery.event.handle after hanging on the event object. As an example
Copy Code code as follows:

function fn1 () {
Console.log (1)
}
function fn2 () {
Console.log (2)
}
$ (document). Bind (' click.a ', fn1);
$ (document). Bind (' click ', fn2);
$ (document). Trigger (' click! '); 2

Added two click events for document, one with namespace "click.a" and one without "click". Use trigger when the parameter click Add an exclamation mark "!". An event that does not trigger a namespace can be seen from the output of 2. To sum up:
. Trigger (' click ') triggers all click events
. Trigger (' click.a ') triggers only click events for "CLICK.A"
. Trigger (' click! ') triggers a non-namespace click event
Then look.
Copy Code code as follows:

if (Type.indexof (".") >= 0) {
Namespaced Trigger; Create a regexp to match event type in handle ()
namespaces = Type.split (".");
Type = Namespaces.shift ();
Namespaces.sort ();
}

This paragraph is very well understood, that is, the processing of. Trigger (' click.a '), that is, the handling of namespace events.
Then look.
Copy Code code as follows:

if ((!elem | | jquery.event.customevent[type]) &&!jquery.event.global[type]) {
No jQuery handlers for this event type, and it can ' t have inline handlers
Return
}

For special events such as "GetData" or for events that have been triggered, return directly.
Down
Copy Code code as follows:

event = typeof Event = = = "Object"?
Jquery.event Object
event[Jquery.expando]? Event:
Object literal
New Jquery.event (Type, Event):
Just the event type (string)
New Jquery.event (type);

There are three kinds of situations
, the event itself is an instance of the Jquery.event class
, event is a common JS object (an instance of a Jquery.event class)
, the event is a string, such as "click"
Continued
Event.type = type;
Event.exclusive = exclusive;
Event.namespace = Namespaces.join (".");
Event.namespace_re = new RegExp (^|\\.) + Namespaces.join ("\. (?:. *\\.)?") + "(\\.| $)");
Note that Exclusive/namespace/namespace_re is hooked up to the event and can be used in JQuery.event.handle (event namespace).
Down is
Copy Code code as follows:

Triggerhandler () and global events don ' t bubble or run the default action
if (onlyhandlers | |!elem) {
Event.preventdefault ();
Event.stoppropagation ();
}

Onlyhandlers is used only in. Triggerhandler, which does not trigger the default behavior of the element and stops bubbling.
Below is
Copy Code code as follows:

Handle a global Trigger
if (!elem) {
Todo:stop taunting the data cache; Remove global events and always attach to document
Jquery.each (Jquery.cache, function () {
Internalkey variable is just used to make it easier to find
And potentially change this stuff later; Currently it just
Points to Jquery.expando
var Internalkey = Jquery.expando,
Internalcache = this[Internalkey];
if (Internalcache && internalcache.events && internalcache.events[type]) {
JQuery.event.trigger (event, data, InternalCache.handle.elem);
}
});
Return
}

Here is a recursive call. If there is no elem element, then take it from the Jquery.cache.
Followed by
Copy Code code as follows:

Don ' t does events on text and comment nodes
if (Elem.nodetype = = 3 | | elem.nodetype = = 8) {
Return
}

property, the text node returns directly.
Below is
Copy Code code as follows:

Clone any incoming data and prepend the event, creating the handler arg list
data = Data!= null? Jquery.makearray (data): [];
Data.unshift (event);

First, the argument data is placed in the array, and the event object is placed in the first position of the array.
Followed by
Copy Code code as follows:

Fire event on the current element, then bubble up the DOM tree
do {
var handle = Jquery._data (cur, "handle");
Event.currenttarget = cur;
if (handle) {
Handle.apply (cur, data);
}
Trigger an inline bound script
if (Ontype && jquery.acceptdata (cur) && cur[ontype] && cur[ontype].apply (cur, data) = = F Alse) {
Event.result = false;
Event.preventdefault ();
}
Bubble up to document, then to window
Cur = Cur.parentnode | | cur.ownerdocument | | Cur = = event.target.ownerDocument && window;
while (cur &&!event.ispropagationstopped ());

This piece of code is important and does the following things
, take handle
Perform
To perform events added by onxxx (such as onclick= "Fun ()")
, take the parent element
The while loop repeats these four steps repeatedly to simulate event bubbling. Until the Window object.
Next up is
Copy Code code as follows:

If Nobody prevented the default action, do it now
if (!event.isdefaultprevented ()) {
var old,
Special = jquery.event.special[Type] | | {};
if (!special._default | | special._default.call (elem.ownerdocument, event) = = False) &&
! (Type = = "click" && jquery.nodename (Elem, "a")) && Jquery.acceptdata (elem)) {
Call a native DOM method on the target with the same name as the event.
Can ' t use a. isfunction () Check here because IE6/7 fails that test.
Ie<9 dies to hidden Element (#1486), may want to revisit a try/catch.
try {
if (Ontype && elem[type]) {
Don ' t Re-trigger an OnFoo event, we call it FOO () method
Old = elem[Ontype];
if (old) {
elem[Ontype] = null;
}
jQuery.event.triggered = type;
elem[type] ();
}
\ catch (ieerror) {}
if (old) {
elem[Ontype] = old;
}
jQuery.event.triggered = undefined;
}
}

This section is a trigger for the browser default behavior. such as Form.submit (), Button.Click () and so on.
Note that because of the security restrictions on links in Firefox, jquery's default behavior for linking is uniformly not triggered. That is, you cannot make a link jump by using the. Trigger ().

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.