Created
November 28, 2016 20:54
-
-
Save indiesquidge/41affa8f9fcf1c99c2f7b993fd6470d9 to your computer and use it in GitHub Desktop.
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
const addEventing = function (obj) { | |
let events = {} | |
obj.on = (eventName, fn) => { | |
if (events[eventName]) { | |
events[eventName].push(fn) | |
} else { | |
events[eventName] = [fn] | |
} | |
} | |
obj.trigger = (eventName, ...args) => { | |
events[eventName].forEach(fn => fn(...args)) | |
} | |
return obj | |
}; | |
// | |
// Make an addEventing mix-in that adds .trigger() and .on() methods to the input object. | |
// | |
// Example: | |
var obj = addEventing({ name: 'John', age: 35 }); | |
obj.on('ageChange', function() { | |
console.log('age changed'); | |
}); | |
obj.trigger('ageChange'); | |
// --> Calling this logs: 'age changed' | |
// | |
// Requirements: | |
// - addEventing should return the original object it was passed. | |
// - It should be able to handle multiple callback functions for the same event name. | |
// - If obj.trigger is called with additional arguments it should pass those to the listeners. | |
// - Note: we don't need to write a way to remove event listeners. | |
// | |
// ---------------------------------------------------- | |
// Example 1: | |
var obj2 = addEventing({ name: 'Bob', age: 30 }); | |
obj2.on('ageChange', function() { | |
console.log('Age changed'); | |
}); | |
obj2.trigger('ageChange'); | |
// --> logs: 'Age changed' | |
// | |
// ---------------------------------------------------- | |
// Example 2: | |
var obj3 = addEventing({ name: 'Bob', age: 30 }); | |
obj3.on('ageChange', function() { | |
console.log('Age changed'); | |
}); | |
obj3.on('ageChange', function() { | |
console.log('Age changed again'); | |
}); | |
obj3.trigger('ageChange'); | |
// --> logs: 'Age changed' | |
// 'Age changed again' | |
// | |
// ---------------------------------------------------- | |
// Example 3: | |
var obj4 = addEventing({ name: 'Bob', age: 30 }); | |
obj4.on('ageChange', function(age) { | |
console.log('Age changed to: ' + age); | |
}); | |
obj4.age++; | |
obj4.trigger('ageChange', obj4.age); | |
// --> logs: 'Age changed to: 31' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment