Created
July 20, 2015 13:20
-
-
Save mhintz/fd83fed0a92e246a99db to your computer and use it in GitHub Desktop.
Super Simple Flux Implementation
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
// The dispatcher has no dependencies. It is a simple event emitter | |
var dispatcher = { | |
listeners: [], | |
emit: function(name, meta) { | |
this.listeners.forEach(function(listener) { | |
listener({ | |
name: name, | |
payload: meta | |
}) | |
}) | |
}, | |
listen: function(listener) { | |
this.listeners.push(listener) | |
} | |
} | |
// The store keeps the state. It listens to events, updates the state, and notifies listeners when it updates | |
var store = { | |
state: { value: 0 }, | |
listeners: [], | |
onAction: function(action) { | |
if (action.name === 'increment') { | |
this.state.value++; | |
} else if (action.name === 'decrement') { | |
this.state.value--; | |
} | |
this.update(); | |
}, | |
getState: function() { | |
// Return a defensive clone to avoid accidentally mutating state | |
return Object.assign({}, this.state); | |
}, | |
listen: function(listener) { | |
this.listeners.push(listener); | |
}, | |
update: function() { | |
this.listeners.forEach(function(listener) { | |
listener(); | |
}); | |
} | |
} | |
// The store depends on the dispatcher and listens to it in one place | |
dispatcher.listen(store.onAction.bind(store)); | |
// Your UI depends on the store and listens to it in one place | |
store.listen(function() { | |
// Update your entire UI here | |
// React.render(<App state={store.getState()} />, rootElement); | |
console.log(store.getState()); | |
}); | |
// Actions depend on the dispatcher and encapsulate certain event emit calls | |
var actions = { | |
increment: function() { | |
dispatcher.emit('increment', {}); | |
}, | |
decrement: function() { | |
dispatcher.emit('decrement', {}); | |
} | |
} | |
// Require the actions around the app and use them to emit events | |
actions.increment(); | |
actions.increment(); | |
actions.increment(); | |
actions.increment(); | |
actions.decrement(); | |
actions.decrement(); | |
actions.decrement(); | |
actions.decrement(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment