Created
June 30, 2016 20:14
-
-
Save mkozhukharenko/784f8d4cf606fd3f7318f7d5f18e95ab to your computer and use it in GitHub Desktop.
Simple Event Emitter Improved
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
// make EE singelton, add .off method | |
let instance = null; | |
class EventEmitter { | |
constructor() { | |
// ensure we have only one instance (singelton pattern) | |
if (!instance) { | |
instance = this; | |
} | |
this.events = {}; | |
return instance; | |
} | |
// unsubscribe | |
off(name, fn) { | |
this.events[name] = this.events[name] || []; | |
let index = this.events[name].indexOf(fn); | |
this.events[name].splice(index, 1); | |
} | |
on(name, fn) { | |
this.events[name] = this.events[name] || []; | |
this.events[name].push(fn); | |
}; | |
trigger(name, args) { | |
this.events[name] = this.events[name] || []; | |
this.events[name].forEach((fn) => fn(args)); | |
}; | |
} |
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
// EE in real life. | |
// Store - it's out model. | |
class Store extends EventEmitter { | |
constructor(initalState) { | |
super() | |
this.__state = initalState; | |
}; | |
get state() { | |
return this.__state | |
}; | |
set state(state) { | |
this.trigger('update', state); | |
this.__state = state; | |
} | |
} | |
var store = new Store({}); | |
store.on('update', function(newState) { | |
console.log('newState', newState); | |
// update DOM | |
}); | |
// set new state | |
store.state = { name: 'Vasya Pupkin' }; | |
store.state = { name: 'Petya Ivanov' }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment