Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining events and DOM iteration

Tags:

jquery

Below I've got two jQuery selectors.

The first searches for a DOM element within a cached object and then searches its parents, then it seaches the parents (table) for another dom element. (ex. 2)

The second (2 lines) searches via the cached element. (ex. 1)

    $('element', table.setting.body).on('blur focus', table.focus).parents('parent').find('another element').on('click', function); // ex2

    $('element', table.setting.body).on('blur focus', function); // ex 1
    $('another element', table.setting.body).on('click', function); // ex 1

Which one is faster/best practice?
Ex. 1 would without doubt be faster reffering to jQuery functions, ie. .hide().animate().show() but, when is it when searching for DOM elements?

enter image description here

like image 808
Christian Werther Avatar asked Sep 27 '12 14:09

Christian Werther


People also ask

What is event loop iteration?

The Event Loop has one simple job — to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, the Event Loop will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.

Are events part of DOM?

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events, which can trigger JavaScript code.

What is event and what is DOM event?

DOM (Document Object Model) Events are a signal that something has occurred, or is occurring, and can be triggered by user interactions or by the browser.


1 Answers

In my opinion this is less a question of speed but more a question of maintainability and good coding style.

And that is where Example 1 is far better than Example 2.

Avoid confusion and keep things separated. You want to attach 2 events to 2 different element - write 2 statements. This makes your code far more structured and readable.

like image 72
Christoph Avatar answered Oct 24 '22 22:10

Christoph