In the jQuery library, the function doesn't exist, yet every jQuery object has these essential methods. In another thread, it was stated that .on() belongs to the node API, which confuses me, since it can be used in the front-end and I don't even need to include const EventEmitter = require('events');
and neither does the jquery.min.js. I just would like to learn about why for example the strings 'click' or 'mouseover' are valid arguments.
Also, the on() method makes extensive use of callback functions.
For example:
$('class').on('click', event => {...})
I would like to understand why it can be passed a lambda function or 'event' as stated above.
Also, some might find the following resource useful, however, it is not really that straightforward and made me come up with more questions than answers: https://nodejs.org/docs/latest/api/events.html
The on() method attaches one or more event handlers for the selected elements and child elements. As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Global variables live until the page is discarded, like when you navigate to another page or close the window. Local variables have short lives. They are created when the function is invoked, and deleted when the function is finished.
But as explained above, in JavaScript, all functions are naturally closures (there is only one exception, to be covered in The "new Function" syntax). That is: they automatically remember where they were created using a hidden [[Environment]] property, and then their code can access outer variables.
on
method registers a handler, which is callback function with specific signature. Once an event is triggered, a handler is called. It receives necessary data as function parameters (commonly event
object).
jQuery and Node event emitter aren't related in any way, they both have on
method because it's a conventional way for a method that adds event handlers.
A naive implementation that shows how it works:
const emitter = {
handlers: {},
on(eventName, handler) {
if (!this.handlers[eventName])
this.handlers[eventName] = [];
this.handlers[eventName].push(handler);
},
emit(eventName, data) {
for (const handler of this.handlers[eventName])
handler(data);
}
};
emitter.on('foo', data => console.log(data.text));
emitter.emit('foo', { text: 'Foo event triggered' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With