Overview
It mainly uses vue-like data binding.
first step
const data = { name: "tom", age: 14 } (data, "name", { get(){ return "name is read" }, set(val){ (‘I've been assigned a value‘,val) } }) //Put this code to the browser console to view the effect( )
The output is not tom, but name is read, because defineProperty's listening hijacking of the name field of data and modified the value that the name field should have returned.
Step 2
const _data = { ...data } for(let i in data){ (data, i, { get(){ return _data[i]+"After modified by js" }, set(val){ _data[i] = val; } }) }
Why do you need a separate _data?
Answer: Listen to the data field and modify the return attribute of the field. The impact is that every time you get the field listened to in the data, the browser will call the value returned by get. If you directly return data[i] in the get, it will cause the browser to keep calling the get method, thus entering a dead loop.
Add more data to data
const data = { name: "tom", age: 14, friend: { "name1": "Zhang San", "name2": "Li Si", "name3": "Wang Wu", "name4": "Zhao Liu" }, }
Format the initial value
const createNewWatch = (val, path, parentKey, event) => { //If the value is not object type, then return this value directly if(typeof val != ‘object‘) return val; //On the contrary, if it is object type, then call WatchObject to traverse and listen to child elements //WatchObject will be created in the following code return WatchObject(val,(parentKey), event) } Guangzhou Brand Design Company
Format object object, listen for value
const WatchObject = (data, path, event) => { function WatchObject(){ for(var key in data){ //Call the function created before and format the val data[key] = createNewWatch(data[key], path, key, event) //Create listening to the data key defineProperty(this, key, data[key], (key), event) } } return new WatchObject() }
Finally, execute the code and a simple data listening is completed.
const b = WatchObject(data,[],{ set(path,val){ (path,val) } })
The above is the detailed content of how to implement simple data monitoring using JS. For more information about JS data monitoring, please pay attention to my other related articles!