How to build an event system

Starts with Meteor. Meteor is awesome because it is reactive. More specifically, client side painting –reactive–> client side db –reactive–> server side db

An reactive system is built on top of an event system, but an event system doesn’t mean it is reactive.

First version:

var game = {};
game.onHomeWin = function(){
  homeTeam.celebrate();
  awayTeam.cry();
};
var homeTeam = {};
homeTeam.celebrate = function(){
  console.log("YEAH!");
};
var awayTeam = {};
awayTeam.cry = function(){
  console.log("55555");
};

//on home win event
//something else triggers the homeWin event
//game responds to the event
game.onHomeWin();

Second version:

//refactor game.onHomeWin
var game = {};
game.listOfThingsToDo = [];
game.onHomeWin = function(callback){
  game.listOfThingsToDo.push(callback);
};
game.triggerHomeWin = function(){
  for(var i=0; i<game.listOfThingsToDo.length; i++){
    game.listOfThingsToDo[i].call();
  }
};

//old code copied and pasted
var homeTeam = {};
homeTeam.celebrate = function(){
  console.log("YEAH!");
};
var awayTeam = {};
awayTeam.cry = function(){
  console.log("55555");
};

//to use
//register interests
game.onHomeWin(homeTeam.celebrate);
game.onHomeWin(awayTeam.cry);
//trigger the event
game.triggerHomeWin();

Third version:

//refactor game.onHomeWin to game.on
var game = {};
game.events = {};
game.on = function(event, callback){
  game.events[event] = game.events[event] || [];
  game.events[event].push(callback);
};
game.trigger = function(event){
  for(var i=0; i<game.events[event].length; i++){
    game.events[event][i].call();
  }
};

//old code copied and pasted
var homeTeam = {};
homeTeam.celebrate = function(){
  console.log("YEAH!");
};
var awayTeam = {};
awayTeam.cry = function(){
  console.log("55555");
};

//to use
//register interests
game.on('homeWin', homeTeam.celebrate);
game.on('homeWin', awayTeam.cry);
//trigger the event
game.trigger('homeWin');

Fourth version – mixin:

var evented = function(input){
  output = {};
  output.events = {};
  output.on = function(event, callback){
    output.events[event] = output.events[event] || [];
    output.events[event].push(callback);
  };
  output.trigger = function(event){
    for(var i=0; i<output.events[event].length; i++){
      output.events[event][i].call();
    }
  };
  _(input).extend(output);
  return input;
};
Advertisements
Standard