Skip to content

Instantly share code, notes, and snippets.

@orlando
Last active October 24, 2016 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save orlando/e31b05af4f730b7832ff1e5dcca90f5f to your computer and use it in GitHub Desktop.
Save orlando/e31b05af4f730b7832ff1e5dcca90f5f to your computer and use it in GitHub Desktop.
Poors man EventSupport example
class EventSupport {
constructor(props) {
this.parent = props.parent;
this.name = props.name;
this.eventQueue = {};
}
trigger(eventName, props) {
if (typeof props === 'undefined') {
props = {};
}
if (!this.eventQueue[eventName]) {
return;
}
this.eventQueue[eventName].forEach(callback => callback.call(this, props))
if (this.parent) {
this.parent.trigger(eventName, props);
}
}
bind(eventName, callback) {
if (!this.eventQueue[eventName]) {
this.eventQueue[eventName] = [];
}
this.eventQueue[eventName].push(callback);
}
}
class Node extends EventSupport {
constructor(props) {
super(props)
}
}
let parentNode = new Node({name: 'Parent'});
let childNode = new Node({parent: parentNode, name: 'Child'});
parentNode.bind('hi', function () {
console.log(this.name, 'says Hi!');
})
childNode.bind('hi', function () {
console.log(this.name, 'says Hi!');
})
childNode.trigger('hi'); =>
// Child says Hi!
// Parent says Hi!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment