Read jQuery 14th (Core Method for triggering events) _ jquery-js tutorial

Source: Internet
Author: User
Trigger event, or simulate user action. For example, you can use the code to simulate user clicks. The result is the same as that of a real mouse click. In the evolution of the event module, I used dispatchEvent (standard) and fireEvent (IE) to actively trigger events. As follows:

The Code is as follows:


...
Dispatch = w3c?
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 another mechanism.
JQuery. event. trigger is the core method for jQuery to trigger events. It provides two trigger event methods for client programmers:. trigger/. triggerHandler

An event may cause two actions in some elements. One is the default action and the other is the event handler. For example, link
Sina mail
Click 1 (event handler) and click OK to jump to mail.sina.com.cn. Therefore, the function designed to trigger events must take these two situations into account.
JQuery uses. trigger and. triggerHandler to distinguish these two situations:
. Trigger execution event hanlder/execute bubble/execute default behavior
. TriggerHandler: Execute the event handler/do not bubble/do not execute the default behavior

The Code is as follows:


The source code of. trigger/. triggerHandler 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 );
}
},


We can see that both of them call jQuery. event. trigger. When the call is performed, either of them is true or not. If the triggerHander parameter is set to true, only the event handler is executed.
In addition, pay attention to the difference:. trigger is an operation on the jQuery object set, while. triggerHandler only operates on the first element of the jQuery object. As follows:

The Code is as follows:


P1


P1


P1


Script
$ ('P'). click (function () {alert (1 )});
$ ('P'). trigger ('click'); // trigger three times, that is, all three p clicks are triggered.
$ ('P'). triggerHandler ('click'); // only play once, that is, only the click of the first p is triggered.
Script


Okay, it's time to post the jQuery. event. trigger code.

The Code is 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. The following list

The Code is as follows:


If (type. indexOf ("! ")> = 0 ){
// Exclusive events trigger only for the exact event (no namespaces)
Type = type. slice (0,-1 );
Exclusive = true;
}


This section is for processing. trigger ('click! ') Is used to trigger non-namespace events. The variable exclusive is mounted to the event object and used in jQuery. event. handle. For example

The Code is 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


Two click events are added to the document. One is "click. a" with a namespace, and the other is not "click ". Add an exclamation point after clicking the trigger parameter "! ". The output result 2 shows that the namespace event is not triggered. Summary:
. Trigger ('click') triggers all click events
. Trigger ('click. A') only triggers click..
. Trigger ('click! ') Triggers a non-namespace Click Event
See

The Code is 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 section is very understandable, that is, processing of. trigger ('click. A'), that is, processing of namespace events.
See

The Code is 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 events that have been triggered, return directly.
Down

The Code is 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 cases
Event itself is an instance of the jQuery. Event class.
, Event is a common js object (non-jQuery. Event class instance)
, 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 mounted to the event, which can be used in jQuery. event. handle (event namespace ).
Next is

The Code is as follows:


// TriggerHandler () and global events don't bubble or run the default action
If (onlyHandlers |! Elem ){
Event. preventDefault ();
Event. stopPropagation ();
}


OnlyHandlers is only used in. triggerHandler, that is, it does not trigger the default behavior of elements and stops bubbling.
Below is

The Code is 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 the elem element is not transmitted, It is retrieved from jQuery. cache.
Next

The Code is as follows:


// Don't do events on text and comment nodes
If (elem. nodeType = 3 | elem. nodeType = 8 ){
Return;
}


Attribute. The text node returns the result directly.
Below is

The Code is as follows:


// Clone any incoming data and prepend the event, creating the handler arg list
Data = data! = Null? JQuery. makeArray (data): [];
Data. unshift (event );


Put the parameter data in the array, and the event object in the first position of the array.
Next

The Code is 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) === false ){
Event. result = false;
Event. preventDefault ();
}
// Bubble up to document, then to window
Cur = cur. parentNode | cur. ownerDocument | cur === event.tar get. ownerDocument & window;
} While (cur &&! Event. isPropagationStopped ());


This code is very important and has done the following:
, Handle
, Execute
, Execute the event (such as onclick = "fun ()") that is added through the onXXX method ()")
, Take the parent Element
The while LOOP repeats these four steps to simulate event bubbles. Until the window object.
Next is

The Code is 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 an. isFunction) () check here because IE6/7 fails that test.
// IE <9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
Try {
If (ontype & elem [type]) {
// Don't re-trigger an onFOO event when we call its 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 triggers the default browser behavior. Such as form. submit () and button. click.
Note: Due to the security restrictions of links in Firefox, jQuery's default behavior on links is always one and cannot be triggered. That is, the link cannot be redirected through. 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.