Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

events - triggerHandler vs. trigger in jQuery

Out of curiosity -- what is the purpose of / use cases for jQuery's triggerHandler? As far as I can tell, the only "real" differences between trigger and triggerHandler is whether or not the native event fires, and event bubbling behavior (though triggerHandler's bubbling behavior doesn't seem hard to replicate with trigger in a few more lines of code). What is the advantage to ensuring the native event does not fire?

I'm curious if this is a convenience function or there's a deeper reason it exists, and what why/when I would use it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the Docs at http://api.jquery.com/triggerHandler/

The .triggerHandler() method behaves similarly to .trigger(), with the following exceptions:

  • The .triggerHandler() method does not cause the default behavior of an event to occur (such as a form submission).

Not preventing the default browser actions allow you to specify an action that occurs on focus or select, etc etc etc, that applies a style. Maybe you have a dynamic menu that is Javascript based, so you don't want to apply the style purely with CSS otherwise those with Javascript disabled won't understand why the layout looks odd. You can use something like $('menu1select').triggerHandler('click');

  • While .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.

If you have an event which hides an element onclick for example, and you want to call that function generally, instead of having to specify each element, you can use $('.menu').triggerHandler('click');

  • Events created with .triggerHandler() do not bubble up the DOM hierarchy; if they are not handled by the target element directly, they do nothing.

Prevents propagation, hopyfully don't have to explain this one...

  • Instead of returning the jQuery object (to allow chaining), .triggerHandler() returns whatever value was returned by the last handler it caused to be executed. If no handlers are triggered, it returns undefined

This one should be self explanatory as well...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...