Skip to content

Instantly share code, notes, and snippets.

@jacobp100
Last active August 22, 2016 14:30
Show Gist options
  • Save jacobp100/12e6a01d8da82ebb2dcc3249cb192fb0 to your computer and use it in GitHub Desktop.
Save jacobp100/12e6a01d8da82ebb2dcc3249cb192fb0 to your computer and use it in GitHub Desktop.
const middleware = () => store => {
const fileWatcher = new FileWatcher();
fileWatcher.on('file-changed', filename => {
store.dispatch({ type: 'FILE_CHANGED', filename });
});
// Make sure we're watching files that may be included in the store's initial state
const initialFiles = store.getState().activeFiles;
fileWatcher.watchFiles(initialFiles);
return next => action => {
// Get the state before and after the action was performed
const previousFiles = store.getState().activeFiles;
next(action);
const nextFiles = store.getState().activeFiles;
// See what changed before and after
const filesToUnwatch = _.difference(previousFiles, nextFiles);
const filesToWatch = _.difference(nextFiles, previousFiles);
// Respond to changes
fileWatcher.unwatchFiles(filesToUnwatch);
fileWatcher.watchFiles(filesToWatch);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment