-
-
Save jsaddict/39052716d66c75ca8a85 to your computer and use it in GitHub Desktop.
Revisions
-
tappleby created this gist
Jul 7, 2015 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,26 @@ const composedCreateStore = compose( applyMiddleware( thunkMiddleware, dispatchIdMiddleware, webWorkerMiddleware('/build/worker.js'), () => promiseMiddleware, loggerMiddleware ), createStore ); const redux = composedCreateStore(reducers, {}); redux.dispatch({ type: "COMPUTE_DATA", payload: 10, meta: { background: true } }); // Logged actions: [ {"type": "COMPUTE_DATA", "payload": 10, "meta": {"background": true, "id": "d1", "backgroundTaskId": "j2", "sequence": "begin"}}, {"type": "COMPUTE_DATA", "payload": 20, "meta": {"background": false, "id": "d1", "backgroundTaskId": "j2", "sequence": "complete"}} ] This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,22 @@ import { isFSA } from 'flux-standard-action'; import assign from 'lodash/object/assign' const dispatch = global.postMessage; function mergeMeta(action, meta) { return {...action.meta, ...meta}; } global.onmessage = function (e) { if (isFSA(e.data)) { const action = e.data; setTimeout(() => dispatch({ ...action, payload: action.payload * 2, meta: mergeMeta(action, { sequence: 'complete' }) }), 5000); } }; This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,47 @@ import uniqueId from 'lodash/utility/uniqueId'; import { isFSA } from 'flux-standard-action'; function mergeMeta(action, meta) { return {...action.meta, ...meta}; } export default function webWorkerMiddleware(scriptURL) { let dispatch = null; const worker = new Worker(scriptURL); worker.onmessage = (e) => { if (dispatch && isFSA(e.data)) { dispatch(e.data); } }; return methods => { dispatch = methods.dispatch; return next => action => { if (!isFSA(action) || !action.meta || !action.meta.background) { return next(action); } const backgroundTaskId = uniqueId('bt'); worker.postMessage({ ...action, meta: mergeMeta(action, { backgroundTaskId, background: false }) }); next({ ...action, meta: mergeMeta(action, { backgroundTaskId, sequence: 'begin' }) }); return backgroundTaskId; } } }