Reputation: 13
In my Fluxxor app from within the actions hash I am proxying ajax calls to parse the results. I would like to be be able to dispatch response payloads from within that module. I am told that i can do this by just passing in the flux instance and then i can dispatch like so:
flux.dispatcher.dispatch({type: SomeActionType, payload: somePayload});
my actions.js file:
/**
*actions.js
*/
var api = require('./api');
var constants = require('./constants');
actions = {
someAction() {
/// I want to dispatch some messages from inside the api module
api.get('hello');
// instead of doing it here
this.dispatch(SomeActionType, somePayload);
}
}
module.exports = actions;
I am not sure how to pass the flux instance into the api module short of passing it into the "get" method call on every request which does not feel right.
How do i get the flux instance into the api module?
UPDATE:
I just realized that i have the flux lib in node_modules. Can i just require flux in my api module?
var flux = require('flux')
then i have access to Dispatcher.dispatch.. OR does this violate the spirit of fluxxor?
Upvotes: 1
Views: 219
Reputation: 159105
A common idiom is to make the requests in a third-party module, but dispatch the actions in the action creators. This keeps your web API (which makes the Ajax requests) and the store-specific notifications (used by flux) cleanly separated, and easier to test.
actions = {
someAction() {
api.get('hello')
.then((resp) => {
// success case
this.dispatch(SomeActionType, somePayload);
}, (err) => {
// failure case
this.dispatch(SomeActionType, somePayload);
});
}
}
api = {
get(param) {
return whateverAjax(param);
}
}
However, if you really want to fire the actions from the API, you can create and wire up your dependencies in order, then pass them around. (This also aids testing, because you can pass in mock instances in your tests.)
// api.js
module.exports = (flux) => {
return {
get(param) {
whateverAjax(param).then((resp) => flux.dispatcher.dispatch(...));
}
}
}
// actions.js
module.exports = (api) => {
someAction() {
api.get('hello');
}
}
// whever you init your Fluxxor.Flux object...
var api = require("./api");
var actions = require("./actions");
var flux = new Fluxxor.Flux(stores); // no actions to start
api = api(flux);
actions = actions(api);
flux.addActions(actions);
One additional note: the flux
library you mention at the end of your question is Facebook's Flux library, and doesn't have anything to do with Fluxxor.
Upvotes: 1