R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{Event-Emitter}
The Question
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);
Overview of full functionality
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.
Answer
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);
};
1. Creating the constructor function
var EmmieEmitter = function () {
this.events = {};
};
2. adding listeners
EmmieEmitter.prototype.emmieOn = function (eventStr, fn) {
if (!this.events[eventStr]) {
this.events[eventStr] = [];
}
this.events[eventStr].push(fn);
};
3. Emitting
EmmieEmitter.prototype.emmieEmit = function (eventStr, eventData) {
if (!this.events[eventStr]) {
return;
}
this.events[eventStr].forEach(function (fn) {
fn(eventData);
});
};
4. Remove Listeners
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);
};
Conclusion
EMIT ALLLLL THE EVENTSSSS
Event-Emitter
By es1831
Event-Emitter
- 2,089