Last active
June 20, 2017 21:01
-
-
Save commenthol/a47ff18e9d838d4e27c9d1b479d45513 to your computer and use it in GitHub Desktop.
small flux demo
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 EventEmitter = require('events'); | |
const random = () => ('' + Math.random()).substr(2) | |
class Dispatcher extends EventEmitter { | |
constructor () { | |
super() | |
this.token = `dispatch_${random()}` | |
this.dispatch = this.dispatch.bind(this) | |
} | |
dispatch (payload) { | |
this.emit(this.token, payload) | |
} | |
} | |
class Store extends EventEmitter { | |
constructor (dispatcher) { | |
super() | |
this._listeners = {} | |
this._dispatcher = dispatcher | |
this.emit = this.emit.bind(this) | |
this.__dispatch = this.__dispatch.bind(this) | |
dispatcher.on(dispatcher.token, this.__dispatch) | |
} | |
getDispatcher () { | |
return this._dispatcher | |
} | |
addListener (fn) { | |
let token | |
do { | |
token = random() | |
} while (this._listeners[token]) | |
super.addListener('CHANGE', fn) | |
this._listeners[token] = fn | |
return token | |
} | |
remove (token) { | |
const fn = this._listeners[token] || {} | |
if (fn) { | |
this.removeListener('CHANGE', fn) | |
} | |
} | |
emit () { | |
super.emit('CHANGE') | |
} | |
__dispatch (payload) { | |
throw new Error('needs implementation') | |
} | |
} | |
// ---- implementation ---- | |
class MyStore extends Store { | |
constructor (dispatcher) { | |
super(dispatcher) | |
this.store = {} | |
} | |
__dispatch (payload) { | |
console.log('__dispatch', payload) | |
this.store = payload | |
this.emit() | |
} | |
} | |
class Component { | |
constructor (store) { | |
this._store = store | |
this.onChange = this.onChange.bind(this) | |
this.tokens = [] | |
this.componentDidMount() | |
} | |
componentDidMount () { | |
this.tokens.push(this._store.addListener(this.onChange)) | |
} | |
componentWillUnmount () { | |
this.tokens.forEach((token) => this._store.remove(token)) | |
} | |
onChange () { | |
console.log('onChange', this._store.store, this.tokens) | |
this.tokens.forEach((token) => this._store.remove(token)) | |
} | |
} | |
;(function test () { | |
const dispatcher = new Dispatcher() | |
const store = new MyStore(dispatcher) | |
const comp = new Component(store) | |
dispatcher.dispatch({type: 'TEST', hello: 'world'}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment