Question

I'm in the need of widen my perspective on the framework libraries, to be able to make well aware choices of if/which/when to add a framework to a website.

One thing that got my attention was event handlers, as they seems to be somewhat more complex structured.

For me, in the early days, an event handler were added inline with its element <a onclick="DoSomething();">...</a>

Later on they were removed from being inline and added globally document/element.onlick = "DoSomethingOnClick or document/element.onlick = "function() {...}

As of today, the frameworks add their own mechanism on top and I am trying to grasp what/how that actually means/is done.

By studying code parts it appears to me, and here describe in a VERY simple way, that they add the onclick event similar to above global and then pass the event when raised, into their own handler, which itself is an object structure containing stored/added functions and elements and their relationships.

Is this a correct observation? If not, then how is it done?

Can this be showed with a simple written sample in Javascript?

Based on the following quote,

"You can use the jQuery on method to attach an event handler to the document, and pass it a filter string that will cause your handler only to fire when the event happens on an element that match the filter, and with the matched element as this value."

how is the element that triggered the event identified in the handler (by the event object or ?) and how are the elements to be fired stored/identified?

Do the other frameworks, other than jQuery, have a very much different structure of their implementation of event handlers?

Was it helpful?

Solution

jQuery has an internal queue of all the handlers it has attached for a particular event on a particular element. The first time you bind an event to that element it initializes the queue and uses addEventListener to bind the event to jQuery's generic event-handling function. When the event is triggered, the function uses event.target to determine which element it is, and then finds the queue of handlers associated with it and calls them in the order that they were added.

The on method of delegation is nested on top of this. It takes advantage of event bubbling: when an event occurs, it's triggered on the specific target element and also all its containing elements. You bind the handler to a container, and it saves the selector string in the queue entry. When it's processing that entry in the handler queue, it tests whether event.target (which is still the specific element that you clicked on) matches the selector, and then executes the handler function. This mechanism allows you to bind handlers for elements that have not yet been added to the DOM; it's particularly useful when you have a list of elements that is updated dynamically (e.g. adding rows to a table).

Licensed under: CC-BY-SA with attribution
scroll top