Responsiveness is an important part of the MVVM pattern, where a response to an operation on data gives the opportunity to do the next operation based on the response
Object properties are processed in a responsive manner
// Object properties are processed responsively
function reactiveObject(obj, key, val) {
// If the value of an object is also an object, we will recurse
observe(val);
Object.defineProperty(obj, key, {
get() {
console.log("Get attribute:", key, "Values.", val);
return val;
},
set(newVal) {
if(newVal ! == val) {// Direct assignment needs to be reresponseized
observe(newVal);
console.log("Set property:", key, "Values.", newVal); newVal = val; }}}); }Copy the code
Array reactive processing
// Array response processing
function reactiveArray() {
// Get the original array prototype
const orgArrayProto = Array.prototype;
// Back up the array prototype and override method
const reactiveArrayProto = Object.create(orgArrayProto);
["push"."pop"."shift"."unshift"."splice"."sort"."reverse"].forEach(
(method) = > {
reactiveArrayProto[method] = function() {
// Execute the array primitive method
orgArrayProto[method].apply(this.arguments);
// Trigger change notification
console.log("Array operation: method:", method, " arguments: ".arguments); }; });return reactiveArrayProto;
}
Copy the code
Perform unified responsive processing
// Perform unified response processing
function observe(obj) {
if (typeofobj ! = ="object" || obj == null) {
return;
}
if (Array.isArray(obj)) {
// Perform array responseization
// Override the array prototype
obj.__proto__ = reactiveArray();
for (let i = 0; i < obj.length; i++) { observe(obj[i]); }}else {
// Perform object responseization (loop traversal to responseize each attribute)
Object.keys(obj).forEach((key) = >reactiveObject(obj, key, obj[key])); }}Copy the code
TEST
const person = {
name: "Xiao Ming".age: 18.email: ["[email protected]"].address: { city: "bj"}}; observe(person);//1. Directly manipulate object attributes
//2. Operate on nested objects
//3. Assign an object to a property and read it directly
//4. Operation in array 7
Copy the code