search
HomeWeb Front-endJS TutorialRead jQuery No. 14 (core method of triggering events)_jquery

In The Evolution of the Event Module I used dispatchEvent (standard) and fireEvent (IE) to actively trigger events. As follows

Copy the code 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.
The core method of jQuery triggering events is jQuery.event.trigger. It provides two trigger event methods for client programmers: .trigger/.triggerHandler
Read jQuery No. 14 (core method of triggering events)_jquery
The occurrence of an event in some elements may cause two actions, one is the default behavior , one is event handler. For example, link A
Sina Mail
After clicking, 1 pops up (event handler), click OK to jump (default behavior) to mail.sina.com.cn. Therefore, the function that is designed to trigger the event must take these two situations into consideration.
jQuery uses .trigger and .triggerHandler to distinguish between these two situations:
.trigger executes the event handler/executes bubbling/executes the default behavior
.triggerHandler executes the event handler/does not bubble/does not execute the default behavior
Copy code 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 );
}
} ,

It can be seen that both call jQuery.event.trigger. When calling, one did not pass true and the other did. Passing true triggerHander means that only the event handler will be executed.
In addition, there is one difference to note: .trigger operates on a collection of jQuery objects, while .triggerHandler only operates on the first element of the jQuery object. As follows
Copy the code The code is as follows:

p1


p1


p1


<script> <BR>$('p').click(function(){alert(1)} ); <BR>$('p').trigger('click'); // Play 3 times, that is, the clicks of three p's are triggered. ; // Only play once, that is, only trigger the click of the first p <BR></script>

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

Copy 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, with most of it omitted. Listed below are

Copy the code 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 paragraph is to handle the situation of .trigger('click!'), that is, triggering non-namespace events. The variable exclusive is used within jQuery.event.handle after being hung on the event object. For example

Copy code 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


Added two click events to the document, one with namespace "click.a" and one without "click". When using trigger, add an exclamation mark "!" after the click parameter. It can be seen from the output result of 2 that the event of the namespace is not triggered. To summarize:
.trigger('click') triggers all click events
.trigger('click.a') only triggers the click event of "click.a"
.trigger('click!' ) Trigger non-namespace click events
Then look at
Copy the code 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 paragraph is easy to understand, that is, .trigger('click.a ') processing, that is, processing of events with namespaces.
Then look at
Copy the code 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;
}

Return directly for some special events such as "getData" or for events that have been triggered.
Go down
Copy the code 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 situations
, event itself is an instance of jQuery.Event class
, event is an ordinary js object (not an instance of the jQuery.Event class)
, 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("\.(?:.*\.)?") "( \.|$)");
It should be noted that exclusive/namespace/namespace_re is linked to event and can be used in jQuery.event.handle (event namespace).
The following is
Copy code 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 the element and stops bubbling.
The following is
Copy code 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;
}

This is a recursive call. If the elem element is not passed, it will be taken from jQuery.cache.
Followed by
Copy code The code is as follows:

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

Attribute, text node Return directly.
The following is the copy code
Copy code 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 );

First put the parameter data into the array, and put the event object at the first position of the array.
Followed by
Copy code 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.target.ownerDocument && window;
} while ( cur && !event.isPropagationStopped() );

This code is very Important, do the following things
, get handle
, execute
, execute events added through onXXX (such as onclick="fun()")
, get the parent element
while loop Repeat these four steps to simulate event bubbling. Until the window object.
The following is
Copy code 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 name as the event.
// Can't use an .isFunction)() check here because IE6/7 fails that test.
// IEtry {
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 is the trigger for the browser's default behavior. Such as form.submit(), button.click(), etc.
Note that due to the security restrictions of links in Firefox, jQuery’s default behavior for links is unified to not trigger. That is, the link cannot be jumped through .trigger().
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor