xamples
epeat
ode
pproach
ptimize
est
Your REACTO question today is to implement a familiar Javascript concept:
the EventEmitter. It works like this:
You can create an EventEmitter:
var myEventEmitter = new EventEmitter();
And you can register listeners to different event strings with an on method:
myEventEmitter.on('anImportantEvent', function (eventDetails) {
console.log('Something important just happened!', eventDetails);
});
These listeners get called when the created event emitter emits the event with related data:
myEventEmitter.emit('anImportantEvent', { location: 'Fullstack' });
You can also unregister a listener using a removeListener method:
var fn = function () {
console.log('Cool, my event happened!');
};
// Listener is attached.
myEventEmitter.on('prestoBango', fn);
// Listener is no longer attached and has moved on with its life.
myEventEmitter.removeListener('prestoBango', fn);
var superbowl = new EventEmitter();
var cheer = function (data) {
console.log('RAAAAAHHHH!!!! Go ' + data.scoringTeam);
};
var jeer = function (data) {
console.log('BOOOOOO ' + data.scoringTeam);
};
superbowl.on('touchdown', cheer);
superbowl.on('touchdown', jeer);
superbowl.emit('touchdown', { scoringTeam: 'Patriots' });
// Both cheer and jeer are called with data.
superbowl.removeListener('touchdown', jeer);
superbowl.emit('touchdown', { scoringTeam: 'Seahawks' });
// Only cheer is called.
var EmmieEmitter = function () {
this.events = {};
};
EmmieEmitter.prototype.emmieOn = function (eventStr, fn) {
if (!this.events[eventStr]) {
this.events[eventStr] = [];
}
this.events[eventStr].push(fn);
};
EmmieEmitter.prototype.emmieEmit = function (eventStr, eventData) {
if (!this.events[eventStr]) {
return;
}
this.events[eventStr].forEach(function (fn) {
fn(eventData);
});
};
EmmieEmitter.prototype.emmieRemoveListener = function (eventStr, fn) {
var eventFns = this.events[eventStr];
if (!eventFns) return;
var i = eventFns.indexOf(fn);
if (i === -1) return;
eventFns.splice(i, 1);
};
var EmmieEmitter = function () {
this.events = {};
};
EmmieEmitter.prototype.emmieOn = function (eventStr, fn) {
if (!this.events[eventStr]) {
this.events[eventStr] = [];
}
this.events[eventStr].push(fn);
};
EmmieEmitter.prototype.emmieEmit = function (eventStr, eventData) {
if (!this.events[eventStr]) {
return;
}
this.events[eventStr].forEach(function (fn) {
fn(eventData);
});
};
EmmieEmitter.prototype.emmieRemoveListener = function (eventStr, fn) {
var eventFns = this.events[eventStr];
if (!eventFns) return;
var i = eventFns.indexOf(fn);
if (i === -1) return;
eventFns.splice(i, 1);
};
EMIT ALLLLL THE EVENTSSSS