Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement event-driven JavaScript without involving any DOM element?

Tags:

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.

like image 745
Dwi Ash Avatar asked Apr 03 '11 06:04

Dwi Ash


People also ask

How does event listener work in JavaScript?

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.

Which event occurs when a DOM element receives the cursor?

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.

Why do we need event handler in JavaScript?

Event handlers allow JavaScript code to alter the behavior of windows, of documents, and of the elements that make up those documents.


1 Answers

Sure! The keyword you're looking for is "pubsub". Here are some well-known implementations:

  • As a jQuery plugin
  • PubSubJS
  • EventEmitter2
  • Backbone.Events

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"); 
like image 196
Domenic Avatar answered Sep 18 '22 13:09

Domenic