// 数据存储对象
let data = {
price: 20,
quantity: 5
}
console.log("target=null")
//与data中属性相关的目标函数
let target = null;
// 与data属性有关的每个函数保存在一个数组中
// 添加相关函数到改数组中
// 改变时 把该数组的函数都执行一遍
class Dep {
constructor() {
//订阅者
this.subscribers = [];
}
//给订阅者添加依赖
//target函数是否存在 订阅者是否已经存在
depend() {
console.log("depend函数被调用")
if (target && !this.subscribers.includes(target)) {
console.log("target函数被添加")
this.subscribers.push(target)
}
}
//通知订阅者执行保存的函数
notify() {
console.log("notify被调用")
this.subscribers.forEach(sub => sub());
}
}
//便利data每个属性 填加getter和setter构造器
// 给每个属性添加一个dep实例
//1. 在get中 给订阅者添加依赖 然后该属性的值
//2. 在set中,先改变该属性的值 然后给执行订阅者保存的函数
Object.keys(data).forEach(key=> {
console.log(key+"被重构属性")
// 当前属性的值
let currentVal = data[key];
const dep = new Dep();
Object.defineProperty(data,key,{
get() {
dep.depend();
return currentVal;
},
set(newVal) {
currentVal = newVal;
dep.notify();
}
})
})
//执行target函数 的函数
function watcher(myFunc) {
target = myFunc;
console.log("target函数被调用")
target();
target = null;
}
// 当使用 data.price 和使用 data.quantity时,他们的get函数就被调用
watcher(()=> {
data.total = data.price * data.quantity;
})
vue数据双向绑定原理--初学习笔记
最新推荐文章于 2024-07-31 23:47:49 发布
这篇博客探讨了如何使用JavaScript实现数据响应式变化,通过观察者模式创建了一个订阅-发布系统。文章中,作者定义了一个Dep类来管理订阅者,并在数据对象的属性上添加getter和setter,确保在属性访问时添加依赖并在属性更改时通知订阅者执行相关函数。此外,还介绍了一个watcher函数用于执行目标函数,展示了数据价格和数量变化如何影响计算属性total的更新。
摘要由CSDN通过智能技术生成