Skip to content

Instantly share code, notes, and snippets.

@axetroy
Created December 4, 2020 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axetroy/0d9924f5257869fa1b2bbfea9e7c691a to your computer and use it in GitHub Desktop.
Save axetroy/0d9924f5257869fa1b2bbfea9e7c691a to your computer and use it in GitHub Desktop.
reactive.js
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