Skip to content

Instantly share code, notes, and snippets.

@mhintz
Created July 20, 2015 13:20
Show Gist options
  • Save mhintz/fd83fed0a92e246a99db to your computer and use it in GitHub Desktop.
Save mhintz/fd83fed0a92e246a99db to your computer and use it in GitHub Desktop.
Super Simple Flux Implementation
// 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