Do not use jQuery methods to trigger native events

  • 2020-03-30 02:10:08
  • OfStack

JavaScript frameworks offer so much functionality that you can easily fall into a hole. The more you rely on your library, the more likely it is that a small change in the way you modify or maintain it will affect other functionality, especially when maintaining legacy code that is years old. One of the mistakes I see a lot is the jQuery trigger, which allows developers to manually trigger certain events. This function is really powerful and easy to use, but please abide by the convention, do not trigger those native event names in JS!
Note: I know that other JS frameworks offer this functionality as well -- I'm only using jQuery as an example because I've seen its popularity and recently ran into this problem. All of the tool libraries can cause the same problem. MooTools USES fireEvent, for example.
Here is a typical example of using trigger to complete a task:
//Listen for click events
jQuery('.tabs a').on('click', function() { 
//Perform certain operations, such as switching interfaces, loading content, etc..

//Triggers the click event on the last a tag
jQuery('.tabs a').last().trigger('click'); 

The code above will open the TAB TAB for the given index. I fully understand why developers use triggers to handle these things, usually because the function to trigger is not available globally, and triggering events is easy and always available. The problem is that using native event names to trigger may... The trigger... Some unspeakable wounds. Let's take a look at what's being added elsewhere on the site:
//Listen for all click events within the body
jQuery('body').on('click', 'a', function() { 
//Some business logic can be done here...

//Condition met, do something else!
if(conditionMet) { 
//Refresh the page?
//Open submenu?
//Submit a form?
//. Lamp push,Intel

Now there is a problem -- TAB clicks can be listened for by completely separate parts, which can be tricky to handle. Well, the best solution is to use a custom event name to follow the native event:
//When you listen for the click event, bring the custom event with you
jQuery('.tabs a').on('click tabs-click', function() { 
//TAB, load, etc...

//Triggers a "false" event on the last tag
jQuery('.tabs a').last().trigger('tabs-click'); 

Your event triggers will now no longer conflict with other listeners on the page. Conservative developers told me that you might want to avoid using trigger (and the rest of the library is the same), but at least you should add a custom event name!

Related articles: