Last active
September 1, 2019 14:34
-
-
Save tgroshon/561e19147169d1d0e341 to your computer and use it in GitHub Desktop.
A Flux Dispatcher with an Action Queue sitting on top to allow dispatching actions at any time.
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
/** | |
* Create an ActionQueue and dispatch each synchronously | |
* @author tgroshon | |
* | |
* See an alternate implementation using ASync from | |
* https://github.com/facebook/flux/issues/106 | |
* by fabiozaffani | |
*/ | |
import {Dispatcher} from 'flux' | |
var dispatcher = new Dispatcher() | |
var actionQueue = [] | |
var isProcessing = false | |
function queueAction(payload) { | |
actionQueue.push(payload) | |
if (!isProcessing) { | |
startProcessing() | |
} | |
} | |
function startProcessing() { | |
isProcessing = true | |
while (actionQueue.length > 0) { | |
if (dispatcher.isDispatching()) { | |
return setTimeout(startProcessing, 100) // Be safe; Avoid an Invariant error from Flux | |
} | |
var payload = actionQueue.shift() | |
dispatcher.dispatch(payload) | |
} | |
isProcessing = false | |
} | |
var AppDispatcher = { | |
isProcessing() { | |
return isProcessing | |
}, | |
dispatch(payload) { | |
queueAction(payload) | |
}, | |
register(callback) { | |
return dispatcher.register(callback) | |
} | |
} | |
module.exports = AppDispatcher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment