Created
December 4, 2020 16:51
-
-
Save axetroy/0d9924f5257869fa1b2bbfea9e7c691a to your computer and use it in GitHub Desktop.
reactive.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reactive(val) { | |
const isPrimitive = | |
val instanceof Number || val instanceof String || val instanceof Boolean; | |
return new Proxy( | |
{ | |
[Symbol.toPrimitive]: () => val, | |
valueOf: () => val.valueOf(), | |
toString: () => val.toString(), | |
}, | |
{ | |
get(target, prop, receiver) { | |
if (isPrimitive) { | |
return Reflect.get(target, prop, receiver); | |
} else { | |
if (prop === Symbol.toPrimitive) { | |
return target[prop]; | |
} | |
return Reflect.get(val, prop, receiver); | |
} | |
}, | |
set(target, prop, value, receiver) { | |
if (isPrimitive) { | |
val[prop] = value; | |
} else { | |
return Reflect.set(val, prop, value); | |
} | |
}, | |
} | |
); | |
} | |
var count = reactive(1); | |
console.log(+count); // 1 | |
console.log(++count); // 2 | |
console.log(++count); // 3 | |
console.log(count + ""); // '3' | |
count -= 10; | |
console.log(+count); // -7 | |
// count = 4; | |
console.log(+count); // 4 | |
var form = reactive({ | |
username: "username", | |
password: "password", | |
address: { | |
city: "a", | |
code: 233, | |
}, | |
}); | |
console.log(form.username); | |
form.username = "axetroy"; | |
console.log(form.username); | |
form.address.city = "123123"; | |
console.log(form.address.city); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment