Alexander Solonik
Alexander Solonik

Reputation: 10230

Why change from focus() to trigger('focus')?

I was going through the history of dropdown.js in bootstrap and came across the following change History file on git, here:

$this.focus()   // focus() being changed to trigger('focus');
$this.trigger('focus')

Now, the guy here has left a comment about the change saying:

Makes life for people with custom jQuery builds excluding event aliases much easier.

I don't quite understand what's the difference here between using focus() or trigger('focus'), as for me both have the same effect; why has the author chosen such a change?

Upvotes: 5

Views: 2396

Answers (2)

jinchuika
jinchuika

Reputation: 333

People with custom jQuery builds could create or modify their own focus() functions intended to do whatever they want. Imagine if you create your own focus() which allows lot of parameters and chains multiple callback; it would be a mess when you combine its usage with the jQuery focus() basic function.

When you use a trigger it's qute obvious you're going to trigger an action; in this case, to focus an element.

Beside of that, using the trigger() functions makes the code a little easier to understand.

Upvotes: 3

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

https://github.com/jquery/jquery#modules.

If you are making a custom jQuery build and exclude event/alias module - you won't have shortcuts to events (e.g. .click(), .focus(), .ready(), etc).

So you'll have to use .on('eventName', handler) for event binding and consequently .trigger('eventName') to trigger jQuery event.

Upvotes: 6

Related Questions