Custom Events Model without using DOM events in JavaScript

NTDave picture NTDave · Mar 9, 2013 · Viewed 18.5k times · Source

I'm new to JavaScript and programming in general, and I have some questions about objects and events.

Say I have an object:

var computer = {
    keyboard: {}
}

What I'm looking for is a way to register events to the keyboard object:

computer.keyboard.registerEvent( "keyEscape" );

Fire the event:

computer.keyboard.dispatchEvent( "keyEscape" );

And create event handlers:

computer.keyboard.addEventListener( "keyEscape", function() {...} );

I know how to do this with DOM elements but not objects. Is this something that can be done in JavaScript (maybe with the help of JQuery)?

Even the slightest bit of guidance would be appreciated greatly.

Answer

Mohsen picture Mohsen · Mar 9, 2013

If you want to make a completely stand alone event system without relying on DOM events you can have something like this using reactor pattern

function Event(name){
  this.name = name;
  this.callbacks = [];
}
Event.prototype.registerCallback = function(callback){
  this.callbacks.push(callback);
}

function Reactor(){
  this.events = {};
}

Reactor.prototype.registerEvent = function(eventName){
  var event = new Event(eventName);
  this.events[eventName] = event;
};

Reactor.prototype.dispatchEvent = function(eventName, eventArgs){
  this.events[eventName].callbacks.forEach(function(callback){
    callback(eventArgs);
  });
};

Reactor.prototype.addEventListener = function(eventName, callback){
  this.events[eventName].registerCallback(callback);
};

Use it like DOM events model

var reactor = new Reactor();

reactor.registerEvent('big bang');

reactor.addEventListener('big bang', function(){
  console.log('This is big bang listener yo!');
});

reactor.addEventListener('big bang', function(){
  console.log('This is another big bang listener yo!');
});

reactor.dispatchEvent('big bang');

Live at JSBin