@captaincodeman/rdx-model
Version:
A small wrapper for [rdx](https://github.com/CaptainCodeman/rdx), my tiny Redux alternative, which makes bundling a state model small and simple.
3 lines (2 loc) • 1.61 kB
JavaScript
const t="state";class n extends EventTarget{constructor(t,n){super(),this.state=t,this.reducer=n,this.state=this.reducer(this.state,{})}dispatch(n){const e=new CustomEvent("action",{cancelable:!0,detail:{action:n}});return this.dispatchEvent(e)&&(n=e.detail.action,this.state=this.reducer(this.state,n),this.dispatchEvent(new CustomEvent(t,{detail:{action:n}}))),n}}const e=(t,n)=>n.indexOf("/")>-1?n:t+"/"+n,s=(t,n,s)=>{const o=e(n,s);return t.dispatch[n][s]=n=>{const e={type:o,...void 0!==n&&{payload:n}};return t.dispatch(e)},o},o={},c=[],i={dispatchPlugin:{onModel(t,n,e){t.dispatch[n]={};for(const o in e.reducers)s(t,n,o)}},effectsPlugin:{onModel(t,n,e){if(!e.effects)return;const i=t.dispatch[n],r=e.effects({dispatch:()=>t.dispatch,getState:()=>t.state});for(const e in r){const a=s(t,n,e),d=r[e].bind(i);o[a]?o[a].push(d):o[a]=[d],"init"===e&&c.push(d)}},onStore(n){n.addEventListener(t,t=>{const{action:n}=t.detail,e=o[n.type];e&&queueMicrotask(()=>e.forEach(t=>t(n.payload)))}),c.forEach(t=>t())}}},r=t=>{const s={...t.models},o={...i,...t.plugins};for(const t in o){const n=o[t];n.model&&(s[t]=n.model)}const c={};for(const t in s){const n=s[t],o={};for(const s in n.reducers)o[e(t,s)]=n.reducers[s];c[t]=(t=n.state,e)=>{const s=o[e.type];return s?s(t,e.payload):t}}const r=function(t){return(n={},e)=>{const s={};for(const o in t)s[o]=t[o](n[o],e);return s}}(c),a=t&&t.state,d=new n(a,r);for(const t in o){const n=o[t];if(n.onModel)for(const t in s)n.onModel(d,t,s[t])}for(const t in o){const n=o[t];n.onStore&&n.onStore(d)}return d};export{r as createStore};
//# sourceMappingURL=createStore.js.map