Last active
May 7, 2016 17:00
-
-
Save gregtyler/e1b287485b9be6a8bbc104e5a8a26e86 to your computer and use it in GitHub Desktop.
A component that can be used by modules to give them simple emit/on event systems
This file contains 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
export default function EventManager() { | |
const events = {}; | |
function emit(event) { | |
if (typeof events[event] === 'undefined') return false; | |
for (let i = 0, l = events[event].length; i < l; i++) { | |
events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); | |
} | |
} | |
function on(event, callback) { | |
if (typeof events[event] === 'undefined') events[event] = []; | |
events[event].push(callback); | |
return this; | |
} | |
return { | |
emit: emit, | |
on: on | |
} | |
} |
This file contains 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
import EventManager from './EventManager.js'; | |
var myMod = new SomeModule(); | |
myMod.on('change', function(newValue) { | |
console.log('myMod was changed to ' + newValue); | |
}); | |
myMod.setValue('test'); // "myMod was changed to test" |
This file contains 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
import EventManager from './EventManager.js'; | |
export default function SomeModule() { | |
var events = new EventManager(); | |
var value; | |
function setValue(val) { | |
value = val; | |
events.emit('change', val); | |
} | |
return Object.assign({}, events, { | |
// Public module methods | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment