|
1 | 1 | import { Mutable } from './types';
|
2 | 2 | import isRegularObject from './utils/isRegularObject';
|
3 |
| -import eventBus from './eventBus'; |
| 3 | +import { emit } from './eventBus'; |
4 | 4 |
|
5 | 5 | export function mutable<Value extends any>(initialValue?: Value) {
|
6 |
| - const events = eventBus(); |
7 |
| - |
8 | 6 | const obj = new Proxy(
|
9 | 7 | {
|
10 | 8 | value:
|
11 | 9 | isRegularObject(initialValue) || Array.isArray(initialValue)
|
12 |
| - ? mutableObject(initialValue, (newVal, oldVal) => |
13 |
| - events.change(newVal, oldVal), |
14 |
| - ) |
| 10 | + ? mutableObject(initialValue, handleChange) |
15 | 11 | : initialValue,
|
16 | 12 | },
|
17 | 13 | {
|
18 | 14 | get(target, prop) {
|
19 | 15 | switch (prop) {
|
20 | 16 | case '_mutable':
|
21 | 17 | return true;
|
22 |
| - case 'onChange': |
23 |
| - return (callback: Mutable<Value>['onChange']) => { |
24 |
| - events.changeHandler(callback); |
25 |
| - }; |
26 | 18 | default:
|
27 | 19 | return target.value;
|
28 | 20 | }
|
29 | 21 | },
|
30 |
| - set(...[target, , value]) { |
31 |
| - const prevValue = target.value; |
| 22 | + set(target, prop, value) { |
| 23 | + const oldVal = target.value; |
32 | 24 |
|
33 |
| - if (value !== prevValue) { |
| 25 | + if (value !== oldVal) { |
34 | 26 | target.value = value;
|
35 |
| - events.change(value, prevValue); |
| 27 | + |
| 28 | + handleChange(value, oldVal); |
36 | 29 | }
|
37 | 30 |
|
38 | 31 | return true;
|
39 | 32 | },
|
40 | 33 | },
|
41 |
| - ); |
| 34 | + ) as Mutable<Value>; |
| 35 | + |
| 36 | + function handleChange(newVal: Value, oldVal: any) { |
| 37 | + emit(obj, newVal, oldVal); |
| 38 | + } |
42 | 39 |
|
43 |
| - return obj as Mutable<Value>; |
| 40 | + return obj; |
44 | 41 | }
|
45 | 42 |
|
46 | 43 | function mutableObject<Obj extends object | unknown[]>(
|
|
0 commit comments