当前位置:网站首页>Object.defineProperty实时监听数据变化并更新页面
Object.defineProperty实时监听数据变化并更新页面
2022-08-05 01:03:00 【追逐梦想之路_随笔】
//html
<ul></ul>
//js部分
<script>
var ul = document.querySelector('ul');
var person = { sex: '男', age: '25', name: '王大锤', height: 28, weight: 32 };
const _render = element => {
var str = `<li>姓名:<span>${person.name}</span></li>
<li>性别:<span>${person.sex}</span></li>
<li>年龄:<span>${person.age}</span></li>
<li>身高:<span>${person.height}</span></li>
<li>体重:<span>${person.weight}</span></li>`
element.innerHTML = str;
}
_render(ul);
// 补全代码
// 监听对象入口
function obseve(targetObj){
if(targetObj === null || typeof targetObj !== "object" ){
return targetObj
}
for (const key in targetObj) {
defineReactive(targetObj,key,targetObj[key])
}
}
// 正式劫持和监听对象
function defineReactive(targetObj,key,value){
Object.defineProperty(targetObj,key,{
get(){
return value
},
set(setVal){
if(setVal !== value){
value = setVal
_render(ul)
}
}
})
}
// 传入需要监听的对象
obseve(person)
边栏推荐
- Software Testing Interview Questions: What's the Difference Between Manual Testing and Automated Testing?
- 【七夕如何根据情侣倾听的音乐进行薅羊毛】背景音乐是否会影响情侣对酒的选择
- DDOS攻击真的是无解吗?不!
- PCIe Core Configuration
- 软件测试技术之最有效的七大性能测试技术
- 深度学习原理学习小结 - Self-Attention/Transformer
- Lattice PCIe 学习 1
- 仅3w报价B站up主竟带来1200w播放!品牌高性价比B站投放标杆!
- Activity Recommendation | Kuaishou StreamLake Brand Launch Conference, witness together on August 10!
- 【机器学习】21天挑战赛学习笔记(二)
猜你喜欢
随机推荐
GCC:屏蔽动态库之间的依赖
第十一章 开关级建模
[How to smash wool according to the music the couple listens to during the Qixi Festival] Does the background music affect the couple's choice of wine?
oracle create user
D - I Hate Non-integer Number (count of selected number dp
day14--postman接口测试
VOC格式数据集转COCO格式数据集
Software testing interview questions: How many types of software are there?
LiveVideoStackCon 2022 上海站明日开幕!
Zombie and orphan processes
【机器学习】21天挑战赛学习笔记(二)
【FreeRTOS】FreeRTOS与stm32内置堆栈的占用情况
Day Fourteen & Postman
JUC thread pool (1): FutureTask use
测试工作这么难找吗?今年32,失业2个月,大龄测试工程师接下来该拿什么养家?
Software Testing Interview Questions: What is Software Testing?The purpose and principle of software testing?
EL定时刷新页面中的皕杰报表实例
Software Testing Interview Questions: What Are the Types of Software Testing?
二叉树[全解](C语言)
跨域解决方案









