Comparing version 2.0.2 to 2.0.3
{ | ||
"name": "internal", | ||
"version": "2.0.2", | ||
"version": "2.0.3", | ||
"files": [ | ||
@@ -5,0 +5,0 @@ "**/index.mjs", |
export default proxy; | ||
declare function proxy<T extends Object>(target: T, fn?: () => void): T; | ||
export declare type Proxy<State> = State & { | ||
subscribe(fn: () => void): void; | ||
unsubscribe(fn: () => void): void; | ||
}; | ||
declare function proxy<State extends Object>(target: State): Proxy<State>; |
@@ -8,21 +8,49 @@ 'use strict'; | ||
// Proxy type | ||
// proxy function | ||
function proxy(target, fn) { | ||
function proxy(target) { | ||
if (typeof Proxy === 'undefined') { | ||
throw new Error('proxy: requires ES6 proxies to work properly') | ||
} | ||
const func = fn || (() => {}); | ||
const fns = []; | ||
let dirty = false; | ||
// debounce the trigger | ||
function debounce() { | ||
dirty = true; | ||
raf(trigger); | ||
} | ||
// trigger the subscribers | ||
function trigger() { | ||
if (dirty) { | ||
func(); | ||
if (!dirty) { | ||
return | ||
} | ||
for (let i = 0; i < fns.length; i++) { | ||
fns[i](); | ||
} | ||
dirty = false; | ||
} | ||
return new Proxy(target, { | ||
set: function(_target, property, value) { | ||
// attach subscribe and unsubscribe to the top-level proxy | ||
return Object.assign(proxy2(target, debounce), { | ||
subscribe(fn) { | ||
fns.push(fn); | ||
}, | ||
unsubscribe(fn) { | ||
const i = fns.indexOf(fn); | ||
if (~i) fns.splice(i, 1); | ||
}, | ||
}) | ||
} | ||
// recursive and responsible for the proxying | ||
function proxy2(state, trigger) { | ||
return new Proxy(state, { | ||
set: function(target, property, value) { | ||
// @ts-ignore | ||
target[property] = value; | ||
dirty = true; | ||
raf(trigger); | ||
trigger(); | ||
return true | ||
@@ -34,3 +62,3 @@ }, | ||
if (typeof value === 'object') { | ||
return proxy(value, fn) | ||
return proxy2(value, trigger) | ||
} | ||
@@ -37,0 +65,0 @@ return value |
Sorry, the diff of this file is not supported yet
64716
20
1473