Is there any way to implement event-driven programming in JavaScript, without involving any DOM element? Such as creating an event-handler which executed every time an array get sorted.
The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers. Syntax: element.
First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
Event handlers allow JavaScript code to alter the behavior of windows, of documents, and of the elements that make up those documents.
Sure! The keyword you're looking for is "pubsub". Here are some well-known implementations:
But you could also do it yourself, like so:
window.pubsub = (function () { var eventToListeners = {}; return { sub: function (event, callback) { if (!eventToListeners.hasOwnProperty(event)) { eventToListeners[event] = []; } eventToListeners[event].push(callback); }, pub: function (event, args) { if (eventToListeners.hasOwnProperty(event)) { for (var i = 0; i < eventToListeners[event].length; ++i) { try { eventToListeners[event][i].call(null, args); } catch (e) { if (console && console.error) { console.error(e); } } } } } }; }()); // Sample usage: pubsub.sub("arraySorted", function () { console.log("array was sorted"); }); var myArray = [2, 3, 1]; myArray.sort(); pubsub.pub("arraySorted");
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