web123456

Handwritten vue responsive principle

<script> //rely let Dep = (function() { function Dep() { this.deps = []; // Used to store all dependency watchers }; // Collect dependencies Dep.prototype.addDep = function (watcher) { this.deps.push(watcher); console.log("Collect a list of dependencies", this.deps); }; // Notification dependencies Dep.prototype.notify = function(params) { console.log('params', params) this.deps.forEach(item => { item.update(params); // Notify page update via update in watch }); }; return Dep; })(); // Execute the function body immediately //The entire dependency of the attribute is the watcher let Watcher = (function() { function Watcher(id) { this.id = id; }; Watcher.prototype.update = (value) => { console.log("The data has changed, notify me to update", value) document.getElementById("text").innerText = value; }; return Watcher; })(); let obj = { name: "nihao", age: 18 }; let dep = new Dep(); // Create new data for storing watcher let value = obj.age; // Responsive method Object.defineProperty(obj, "age", { get() { let watcher = new Watcher("1"); // Instantiate a watcher console.log('watcher', watcher) dep.addDep(watcher); // Collect dependencies return value; // The return value cannot be directly, it will overflow }, set(value) { console.log('set call') dep.notify(value); }, }); console.log(obj.age) // Read the age and the get method will be called obj.age = 23; // Change the age and the set method will be called document.getElementById("app").addEventListener("click", () => { obj.age = (Math.random()*20).toFixed(); }) </script>