Skip to content

Instantly share code, notes, and snippets.

@ryanjadhav
Last active December 27, 2015 17:59
Show Gist options
  • Save ryanjadhav/7366955 to your computer and use it in GitHub Desktop.
Save ryanjadhav/7366955 to your computer and use it in GitHub Desktop.
Simple Event Aggregator
// ---- Code ----
var EventAggregator = function() {
this.events = {};
}
EventAggregator.prototype.trigger = function (msg) {
var args = Array.prototype.splice.call(arguments, 1);
for(var i = 0, len = this.events[msg].length; i < len; i++) {
this.events[msg][i].apply(this, args);
}
}
EventAggregator.prototype.on = function (msg, func) {
if (!this.events[msg]) {
this.events[msg] = [];
}
this.events[msg].push(func);
}
EventAggregator.prototype.off = function (msg, func) {
for(var i = 0, len = this.events[msg].length; i < len; i++) {
if (this.events[msg][i] === func) {
this.events[msg].splice(i, 1);
}
}
}
// Givens
var videoPlay = function (url) {
console.log('video played', url);
}
var dimLights = function () {
console.log('lights dimed');
}
var videoPlayAtTimestamp = function(url, timestamp) {
console.log('video played', url, timestamp);
}
// Implement this
var vent = new EventAggregator();
vent.on('video:player:play', function(url) {
videoPlay(url, 'test');
});
vent.on('video:player:play', dimLights);
vent.on('video:player:play', function(url, timestamp) {
videoPlayAtTimestamp(url, timestamp);
});
vent.trigger('video:player:play', 'amazon s3 video url', "13s");
// extra credit
vent.off('video:player:play', dimLights);
vent.trigger('video:player:play', 'amazon s3 video url');
@kirkonrails
Copy link

Nice!

Works great. Thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment