@samsch/subscribe-store
Version:
A simple subscribable store factory
41 lines (37 loc) • 1.05 kB
JavaScript
;
var createStore = function createStore(initialState) {
var store = {
state: initialState || {}
};
var listeners = [];
var replaceState = function replaceState(newState) {
store.state = newState;
listeners.forEach(function (callback) {
return callback(store);
});
};
store.setState = function (updator) {
var newState = typeof updator === 'function' ? updator(store.state) : updator;
replaceState(newState);
};
store.updateState = function (updator) {
var newState = typeof updator === 'function' ? updator(store.state) : updator;
replaceState(Object.assign({}, store.state, newState));
};
store.subscribe = function (callback) {
listeners.push(callback);
return function () {
return store.unsubscribe(callback);
};
};
store.unsubscribe = function (callback) {
var index = listeners.indexOf(callback);
if (index < 0) {
return false;
}
listeners.splice(index, 1);
return store;
};
return store;
};
module.exports = createStore;