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:
141 Answer
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' }); 1