Skip to content

Instantly share code, notes, and snippets.

@hpneo
Created September 7, 2013 00:01
Show Gist options
  • Save hpneo/6471512 to your computer and use it in GitHub Desktop.
Save hpneo/6471512 to your computer and use it in GitHub Desktop.
var Gambit = function(options) {
var events = {};
var EventManager = {
on : function (event_name, fn, once) {
if (once == undefined) {
once = false;
}
if (!(event_name in events)) {
events[event_name] = [];
}
if (once) {
events[event_name] = [fn];
}
else {
events[event_name].push(fn);
}
},
off : function(event_name, all) {
if (all == undefined) {
all = false;
}
if (all) {
events[event_name] = [];
}
else {
events[event_name].pop();
}
},
fire : function(event_name, scope) {
var callback_arguments = Array.prototype.slice.apply(arguments).slice(2),
callbacks = events[event_name],
scope = scope || window,
i = 0;
for (i; i < callbacks.length; i++) {
callbacks = callbacks[i];
callbacks.apply(scope, callback_arguments);
}
},
clear : function() {
events = {};
}
};
this.on = EventManager.on;
this.off = EventManager.off;
this.fire = EventManager.fire;
this.clear = EventManager.clear;
for (e in options.events) {
this.on(e, options.events[e]);
}
};
Gambit.prototype.gameOver = function() {
this.fire('game_over', this, 100);
};
Gambit.prototype.move = function() {
this.fire('before_move', this, 100);
this.fire('after_move', this, 100);
};
Gambit.super = Gambit.prototype;
// Demo
var game = new Gambit({
events : {
game_over : function(total_score) {
console.log('Game over! Your Score is: ' + total_score);
}
}
});
game.gameOver();
game.gameOver = function() {
console.log('Total score: 100');
Gambit.super.gameOver.apply(this);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment