Skip to content

Instantly share code, notes, and snippets.

@lastday154
Created December 2, 2017 12:15
Show Gist options
  • Select an option

  • Save lastday154/9c70bf2592812fc35ade918ff47325fa to your computer and use it in GitHub Desktop.

Select an option

Save lastday154/9c70bf2592812fc35ade918ff47325fa to your computer and use it in GitHub Desktop.
Grab Notifier
class Notifier
{
constructor() {
this.events = [];
}
on(eventName, callback) {
var self = this;
this.events.push(callback);
return {
off: function() {
if (self.events) {
let index = self.events.indexOf(callback);
if (index > -1) {
self.events.splice(index, 1);
}
}
}
};
}
trigger(eventName, ...parameters) {
if (this.events) {
this.events.forEach((event) => {
event(...parameters);
});
}
}
}
/*
Write a Notifier class that supports the following operations:
1. Constructor.
*/
var notifier = new Notifier();
/*
2. Listening to events.
*/
var listenerJohn = notifier.on('MY_EVENT', function (action, item) {
console.log(`John is ${action} ${item}`);
});
var listenerJane = notifier.on('MY_EVENT', function (action, item) {
console.log(`Jane is ${action} ${item}`);
});
/*
3. Triggering of events.
This particular example should lead to both callbacks
above being invoked with 'eating' and 'a burger' as parameters:
*/
console.log('-------');
notifier.trigger('MY_EVENT', 'eating', 'a burger');
// Should see the following in the console:
// John is eating a burger
// Jane is eating a burger
/*
4. Unsubscribing a listener from existing events.
Note that `off` is not a method no `Notifier`.
`listenerJohn` is the reference returned by `on` above.
*/
listenerJohn.off();
notifier.trigger('MY_EVENT', 'eating', 'a burger');
// Only Jane's callback is invoked.
// Jane is eating a burger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment