Last active
December 27, 2015 17:59
-
-
Save ryanjadhav/7366955 to your computer and use it in GitHub Desktop.
Simple Event Aggregator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ---- 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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!
Works great. Thanks for sharing