Created
April 15, 2018 06:09
-
-
Save dmjcomdem/63472be5ffa6a4e81ee499dac30a6f39 to your computer and use it in GitHub Desktop.
simple class EventEmitter
This file contains hidden or 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 EventEmitter { | |
| constructor() { | |
| this.events = {}; | |
| } | |
| on(type, listener) { | |
| this.events[type] = this.events[type] || []; | |
| this.events[type].push(listener); | |
| } | |
| emit(type, arg) { | |
| if (this.events[type]) { | |
| this.events[type].forEach(listener => listener(arg)); | |
| } | |
| } | |
| } | |
| class Model extends EventEmitter { | |
| constructor(items = []) { | |
| super(); | |
| this.items = items; | |
| } | |
| addItem(item) { | |
| this.items.push(item); | |
| this.emit('add', this.items); | |
| return item; | |
| } | |
| } | |
| class Controller { | |
| constructor(model, view) { | |
| this.model = model; | |
| this.view = view; | |
| view.on('add', this.addTodo.bind(this)); | |
| } | |
| addTodo(title) { | |
| const item = this.model.addItem({ | |
| id: Date.now(), | |
| title, | |
| completed: false | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment