alt
Version:
A flux implementation
82 lines (61 loc) • 2.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = makeAction;
var _functions = require('../functions');
var fn = _interopRequireWildcard(_functions);
var _AltUtils = require('../utils/AltUtils');
var utils = _interopRequireWildcard(_AltUtils);
var _isPromise = require('is-promise');
var _isPromise2 = _interopRequireDefault(_isPromise);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function makeAction(alt, namespace, name, implementation, obj) {
var id = utils.uid(alt._actionsRegistry, String(namespace) + '.' + String(name));
alt._actionsRegistry[id] = 1;
var data = { id: id, namespace: namespace, name: name };
var dispatch = function dispatch(payload) {
return alt.dispatch(id, payload, data);
};
// the action itself
var action = function action() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var invocationResult = implementation.apply(obj, args);
var actionResult = invocationResult;
// async functions that return promises should not be dispatched
if (invocationResult !== undefined && !(0, _isPromise2['default'])(invocationResult)) {
if (fn.isFunction(invocationResult)) {
// inner function result should be returned as an action result
actionResult = invocationResult(dispatch, alt);
} else {
dispatch(invocationResult);
}
}
if (invocationResult === undefined) {
utils.warn('An action was called but nothing was dispatched');
}
return actionResult;
};
action.defer = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return setTimeout(function () {
return action.apply(null, args);
});
};
action.id = id;
action.data = data;
// ensure each reference is unique in the namespace
var container = alt.actions[namespace];
var namespaceId = utils.uid(container, name);
container[namespaceId] = action;
// generate a constant
var constant = utils.formatAsConstant(namespaceId);
container[constant] = id;
return action;
}
module.exports = exports['default'];