Skip to content

Instantly share code, notes, and snippets.

@clalimarmo
Created September 15, 2015 16:54
Show Gist options
  • Save clalimarmo/612779bd7fb689258f55 to your computer and use it in GitHub Desktop.
Save clalimarmo/612779bd7fb689258f55 to your computer and use it in GitHub Desktop.
Deep Linking with React + Flux, Task Store, step 1
TaskStore = (function() {
var TaskStore = {};
var state = {};
TaskStore.addChangeListener = function() {
// left as an exercise - hint: event emitters
};
TaskStore.addChangeListener = function() {
// left as an exercise - hint: event emitters
};
TaskStore.selectedTask = function() {
return state.selectedTask;
};
TaskStore.tasks = function() {
// tasks are returned as an array, for convenience in React,
// but stored as an object, for efficiency in managing state
return Object.keys(state.tasks).map(function(taskId) {
return state.tasks[taskId];
});
};
init();
return TaskStore;
function init() {
var router = Router();
router.register(/^\/tasks\/?$/, function() {
state.selectedTask = null;
triggerChangeEvent();
});
router.register(/^\/tasks\/(\d+)\/?$/, function(path, matcher) {
var taskId = path.match(matcher)[1];
state.selectedTask = state.tasks[taskId];
});
Dispatcher.register(function(action) {
switch (action.type) {
case 'initialize app':
loadTasks();
router.route(action.path);
break;
case 'navigate':
router.route(action.path);
break;
}
}
function triggerChangeEvent() {
// left as an exercise - this should trigger the callbacks added
// via the addChangeListener method
}
function loadTasks() {
state.tasks = [];
// left as an exercise: add mock task data, or integrate with API
triggerChangeEvent();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment