当前位置:网站首页>Object. Can defineproperty also listen for array changes?
Object. Can defineproperty also listen for array changes?
2022-06-25 08:48:00 【InfoQ】
Brief introduction
Object.definePropertyVue2Object.definePropertyObject.definePropertyVue2Basic usage
Object.defineProperty()grammar
Object.defineProperty(obj, prop, descriptor)
objThe object to define the property .
propThe name of the property to be defined or modified orSymbol.
descriptorProperty descriptor to define or modify .
const data = {}
let name = ' Thunder monkey '
Object.defineProperty(data, 'name', {
get() {
console.log('get')
return name
},
set(newVal) {
console.log('set')
name = newVal
}
})
console.log(data.name)
data.name = ' Shark chilli '
console.log(data.name)
console.log(name)
get
Thunder monkey
set
Shark chilli
Shark chilli
data.namenamenamedata.namenameconst data = {}
Object.defineProperty(data, 'name', {
value: ' Thunder monkey ',
writable: false
})
data.name = ' Shark chilli '
delete data.name
console.log(data.name)
data.namedata.name Thunder monkey Object.definePropertyDeep monitoring
// Trigger update view
function updateView() {
console.log(' View update ')
}
// Redefining properties , Listen up ( The core )
function defineReactive(target, key, value) {
// Deep monitoring
observer(value)
// The core API
Object.defineProperty(target, key, {
get() {
return value
},
set(newValue) {
if (newValue != value) {
// Deep monitoring
observer(newValue)
// Set new value
// Be careful ,value Always in closures , After setting here , Again get It will also get the latest value
value = newValue
// Trigger view update
updateView()
}
}
})
}
// Deep monitoring
function observer(target) {
if (typeof target !== 'object' || target === null) {
// Not an object or an array
return target
}
// Redefine each attribute (for in You can also iterate over groups )
for (let key in target) {
defineReactive(target, key, target[key])
}
}
// Prepare the data
const data = {
name: ' Thunder monkey '
}
// Start listening
observer(data)
// test 1
data.name = {
lastName: ' Shark chilli '
}
// test 2
data.name.lastName = ' Cockroach bully '
updateViewDOMVueObject.definePropertysetobserver(newValue)observerdefineReactiveListening array
key Subscript - Determine whether the data to be monitored is an array
- Is an array , Just simulate the array as an object
- Bind the method name of the array to the newly created object
- Assign the method corresponding to the array prototype to the custom method
// Trigger update view
function updateView() {
console.log(' View update ')
}
// Redefine array prototypes
const oldArrayProperty = Array.prototype
// Create new objects , Prototype pointing oldArrayProperty, Extending the new method will not affect the prototype
const arrProto = Object.create(oldArrayProperty);
['push', 'pop', 'shift', 'unshift', 'splice'].forEach(methodName => {
arrProto[methodName] = function() {
updateView() // Trigger view update
oldArrayProperty[methodName].call(this, ...arguments)
}
})
// Redefining properties , Listen up ( The core )
function defineReactive(target, key, value) {
// Deep monitoring
observer(value)
// The core API
Object.defineProperty(target, key, {
get() {
return value
},
set(newValue) {
if (newValue != value) {
// Deep monitoring
observer(newValue)
// Set new value
// Be careful ,value Always in closures , After setting here , Again get It will also get the latest value
value = newValue
// Trigger view update
updateView()
}
}
})
}
// Listening object properties ( entrance )
function observer(target) {
if (typeof target !== 'object' || target === null) {
// Not an object or an array
return target
}
// In the case of arrays
if (Array.isArray(target)) {
target.__proto__ = arrProto
}
// Redefine each attribute (for in You can also iterate over groups )
for (let key in target) {
defineReactive(target, key, target[key])
}
}
// Prepare the data
const data = {
nums: [10, 20, 30]
}
// Monitor data
observer(data)
data.nums.push(4) // Listening array
Array.prototype.push = function() {
updateView()
...
}
ArrayObject.defineProperty['push', 'pop', 'shift', 'unshift', 'splice']Comprehensive code
// Deep monitoring
function updateView() {
console.log(' View update ')
}
// Redefine array prototypes
const oldArrayProperty = Array.prototype
// Create new objects , Prototype pointing oldArrayProperty, Extending the new method will not affect the prototype
const arrProto = Object.create(oldArrayProperty);
// arrProto.push = function () {}
// arrProto.pop = function() {}
['push', 'pop', 'shift', 'unshift', 'splice'].forEach(methodName => {
arrProto[methodName] = function() {
updateView() // Trigger view update
oldArrayProperty[methodName].call(this, ...arguments)
}
})
// Redefining properties , Listen up ( The core )
function defineReactive(target, key, value) {
// Deep monitoring
observer(value)
// The core API
// Object.defineProperty Does not have the ability to listen to arrays
Object.defineProperty(target, key, {
get() {
return value
},
set(newValue) {
if (newValue != value) {
// Deep monitoring
observer(newValue)
// Set new value
// Be careful ,value Always in closures , After setting here , Again get It will also get the latest value
value = newValue
// Trigger view update
updateView()
}
}
})
}
// Listening object properties ( entrance )
function observer(target) {
if (typeof target !== 'object' || target === null) {
// Not an object or an array
return target
}
if (Array.isArray(target)) {
target.__proto__ = arrProto
}
// Redefine each attribute (for in You can also iterate over groups )
for (let key in target) {
defineReactive(target, key, target[key])
}
}
summary
Vue 2shortcoming
- Deep monitoring , You need to recurse to the end , A large amount of calculation
- Unable to listen for new properties / Delete attribute ( So we need to use Vue.set and Vue.delete)
- Cannot listen to native arrays , Require special treatment
Vue 3Object.definePropertyProxyProxyVue 2Vue 3边栏推荐
- RMB 3000 | record "tbtools" video, make a friend and get a cash prize!
- 《乔布斯传》英文原著重点词汇笔记(五)【 chapter three 】
- mysql之Unknown table ‘COLUMN_STATISTICS‘ in information_schema (1109)
- compiling stm32f4xx_it.c... “.\Objects\BH-F407.axf“ - 42 Error(s), 1 Warning(s).
- 某次比赛wp
- 【操作教程】TSINGSEE青犀视频平台如何将旧数据库导入到新数据库?
- Is it safe to open a stock account through the account opening QR code of the account manager? Or is it safe to open an account in a securities company?
- 故障:Outlook 收发邮件时的 0x800CCC1A 错误
- 城链科技平台,正在实现真正意义上的价值互联网重构!
- Sharepoint:sharepoint server 2013 and adrms Integration Guide
猜你喜欢

在二叉树(搜索树)中找到两个节点的最近公共祖先(剑指offer)

C#启动程序传递参数丢失双引号,如何解决?

(translation) the use of letter spacing to improve the readability of all capital text

Unity addressable batch management

Paper:Generating Hierarchical Explanations on Text Classification via Feature Interaction Detection

声纹技术(六):声纹技术的其他应用

City Chain technology platform, really Realizing value Internet reconstruction!

微信小程序_7,项目练习,本地生活

初识生成对抗网络(11)——利用Pytorch搭建WGAN生成手写数字

Easyplayer streaming media player plays HLS video. Technical optimization of slow starting speed
随机推荐
How to implement a system call
Hyper-v:Hyper-v 第 1 代或第 2 代虚拟机
关于I/O——内存与CPU与磁盘之间的关系
Various synchronous learning notes
城鏈科技平臺,正在實現真正意義上的價值互聯網重構!
【总结】1361- package.json 与 package-lock.json 的关系
初识生成对抗网络(12)——利用Pytorch搭建WGAN-GP生成手写数字
35岁腾讯员工被裁员感叹:北京一套房,存款700多万,失业好焦虑
What is the role of software validation testing? What is the price of the confirmation test report?
How to design test cases
对常用I/O模型进行比较说明
[515. find the maximum value in each tree row]
软件工程复习题
【515. 在每个树行中找最大值】
现在网上开通股票账号安全吗?
atguigu----17-生命周期
[summary] 1361- package JSON and package lock JSON relationship
配置、软件配置项、软件配置管理项辨析
打新债真的安全吗? 风险大吗
Hyper-v:hyper-v generation 1 or generation 2 virtual machines