Last active
October 24, 2016 22:00
-
-
Save orlando/e31b05af4f730b7832ff1e5dcca90f5f to your computer and use it in GitHub Desktop.
Poors man EventSupport example
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
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