@tacky/store
Version:
State management framework based on react
87 lines (71 loc) • 2.71 kB
JavaScript
import { store } from '../core/store';
import { CURRENT_MATERIAL_TYPE } from '../const/symbol';
import { bind, convert2UniqueString } from '../utils/common';
import { EMaterialType } from '../interfaces';
import { invariant } from '../utils/error';
import { quacksLikeADecorator } from '../utils/decorator';
import { materialCallStack } from '../core/domain';
function createMutation(target, name, original, isAtom) {
var stringMethodName = convert2UniqueString(name);
return function () {
this[CURRENT_MATERIAL_TYPE] = EMaterialType.MUTATION;
materialCallStack.push(this[CURRENT_MATERIAL_TYPE]);
for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
payload[_key] = arguments[_key];
}
store.dispatch({
name: stringMethodName,
payload: payload,
type: EMaterialType.MUTATION,
domain: this,
original: bind(original, this),
isAtom: isAtom
});
materialCallStack.pop();
var length = materialCallStack.length;
this[CURRENT_MATERIAL_TYPE] = materialCallStack[length - 1] || EMaterialType.DEFAULT;
};
}
/**
* decorator @mutation, update state by mutation styling.
*/
export function mutation() {
var isAtom = false;
var decorator = function decorator(target, name, descriptor) {
// typescript only: @mutation method = () => {}
if (descriptor === void 0) {
var mutationFunc;
Object.defineProperty(target, name, {
enumerable: true,
configurable: true,
get: function get() {
return mutationFunc;
},
set: function set(original) {
mutationFunc = createMutation(target, name, original, isAtom);
}
});
return;
} // babel/typescript: @mutation method() {}
if (descriptor.value !== void 0) {
var original = descriptor.value;
descriptor.value = createMutation(target, name, original, isAtom);
return descriptor;
} // babel only: @mutation method = () => {}
var initializer = descriptor.initializer;
descriptor.initializer = function () {
invariant(!!initializer, 'The initializer of the descriptor doesn\'t exist, please compile it by using babel and correspond decorator plugin.');
return createMutation(target, name, initializer && initializer.call(this), isAtom);
};
return descriptor;
};
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
if (quacksLikeADecorator(args)) {
// @mutation
return decorator.apply(null, args);
} // @mutation(args)
isAtom = args[0] !== void 0 ? args[0] : false;
return decorator;
}