当前位置:网站首页>Wechat applet implements the data listener watch, including the watch that destroys the watch and sub attributes
Wechat applet implements the data listener watch, including the watch that destroys the watch and sub attributes
2022-06-29 09:51:00 【milugloomy】
reason
In the last article 《 Wechat applet implements data listener , similar vue Of watch, replace Observer》 in , What we achieve watch function , But it is still a little troublesome to use . Can it be like Vue That way, just write watch Attribute? ? Certainly. , This is the purpose of writing this blog . We want to achieve the following goals :
- Support changes in listening objects , Listen for changes in the child properties of the object , Support immediate execution
- A few lines of code will introduce , Do not modify the previous code structure , You don't need to introduce... On every page
- Usage and vue Of watch equally
- You can log out when the page is destroyed watch, To reduce overhead
On components and Page To realize
Wechat applet implementation watch function , There are four key points :
- When listening for sub attribute changes ,watch Of key Be similar to 'a.b.c.d', Need to parse this key, In the following parseKey Function .
- watch The function should be in the attached Life cycle and page Of onLoad Implementation in life cycle . One reason is to get this, Another reason is that Component On initialization , Yes data and properties Two places where data can be defined . And in the created In the life cycle , Will properties The properties in are copied to data in . So we are created The next stage of ,attached Listen only data Property changes in , Without listening data and properties The properties of the two objects change , Reduce implementation complexity .
- watch The principle is to use Object.defineProperty Of set Method to listen for changes in values .
- The destruction watch The plan , You can save the value of this attribute with a temporary variable , Delete this property , Re assign .
Create a new one watch.js file , The contents are as follows :
function initComponent() {
let oldComponent = Component
Component = function(obj) {
let oldAttached = obj.attached || function() {}
let oldDetached = obj.detached || function() {}
// stay attached In the initialization watch
obj.attached = function() {
obj.watch && initWatch.call(this, obj.watch)
oldAttached.call(this, ...arguments)
}
// stay detached The cancellation watch
obj.detached = function() {
obj.watch && unWatch.call(this, obj.watch)
oldDetached.call(this, ...arguments)
}
return oldComponent(obj)
}
}
function initPage() {
let oldPage = Page
Page = function(obj) {
let oldOnLoad = obj.onLoad || function() {}
let oldOnUnload = obj.onUnload || function() {}
// stay onLoad In the initialization watch
obj.onLoad = function() {
obj.watch && initWatch.call(this, obj.watch)
oldOnLoad.call(this, ...arguments)
}
// stay onUnload The cancellation watch
obj.onUnload = function() {
obj.watch && unWatch.call(this, obj.watch)
oldOnUnload.call(this, ...arguments)
}
return oldPage(obj)
}
}
function initWatch(watch) {
let that = this
// If obj Yes watch This attribute , Traverse watch object
for (let key in watch) {
// Temporary objects ,tmpObj It's made up of three parts ,obj,key,value;obj={key:value}
let tmpObj = parsePath.call(this, key)
// If watch Of key stay data perhaps properties There are definitions. , Just monitor its changes
if (tmpObj && tmpObj.key) {
// Temporary data , be used for get
let tmpData = tmpObj.value
// watch The callback
let cb = watch[key]
let immediate = false
if (typeof cb === 'object') { // watch: {xxx: {immediate: true, handler: function(){}}}
immediate = cb.immediate
cb = cb.handler
}
// If immediate by true, First execute a method to listen for changes
if (immediate) {
cb.call(that, tmpData)
}
// To configure watch
Object.defineProperty(tmpObj.obj, tmpObj.key, {
set: function(newVal) {
// Save old values , for watch The listener uses
let oldVal = tmpData
// Modify the current value , That is to say this.data.xxx The value of the change , Will call the following get Method to get
tmpData = newVal
// When the data changes , Execute the method again
if (oldVal !== newVal) {
cb.call(that, newVal, oldVal)
}
},
get: function() {
return tmpData
}
})
}
}
}
function unWatch(watch) {
for (let key in watch) {
let tmpObj = parsePath.call(this, key)
// Delete this property , Re assign , You can log out watch
if (tmpObj && tmpObj.key) {
let tmp = tmpObj.obj[tmpObj.key]
delete tmpObj.obj[tmpObj.key]
tmpObj.obj[tmpObj.key] = tmp
}
}
}
// analysis watch Of key, You can resolve sub attributes of an object 'user.address.city' such
function parsePath(key) {
let parent = that.data
let obj = that.data
let segments = key.split('.')
for (var i = 0; i < segments.length; i++) {
if (obj.hasOwnProperty(segments[i]) === false) {
return null
}
parent = obj
obj = obj[segments[i]]
}
return {
obj: parent, //defineProperty The first parameter of
key: segments[i - 1], //defineProperty Second parameter of
value: obj // value
}
}above , The main key code has been annotated .
introduce
One sentence introduces , stay app.js Introduction in watch.js
import './utils/watch.js'Usage mode
Usage and Vue equally , Three watch The example code of the usage mode is as follows :
Page({
data: {
patient: null,
patientList: null
},
onLoad: function(options) {
app.formRequest('/chronic/selectPatientList').then(res => {
this.setData({
patientList: res.body.list
})
})
},
watch:{
//watch object
patientList: function(val) {
console.log('patientList Changed ')
console.log(val)
},
//watch object , Execute now
patient: {
immediate: true,
handler: function(val){
console.log('patient Changed ')
console.log(val)
}
},
//watch Object's child properties
'patient.patientId': function(val) {
console.log('patientId Changed ')
console.log(val)
},
}
})summary
This article , We're in the small program Page and Component Implemented in the watch function , And achieved the first four goals .
边栏推荐
- 微信小程序重写Page函数,实现全局日志记录
- Is it safe to open an account for stock speculation? Is it reliable?
- Do you know what BFD is? This article explains the principle and usage scenarios of BFD protocol in detail
- Please use the learned knowledge to write a program to find out the password hidden in the long string below. The burial point of the password conforms to the following rules:
- 商业智能BI的未来,如何看待AI+BI这种模式?
- UE4 VS的Visual Assist插件设置
- Deep Learning-based Automated Delineation of Head and Neck Malignant Lesions from PET Images
- linux环境下安装配置redis,并设置开机自启动
- 用户级线程和内核级线程
- 監控數據源連接池使用情况
猜你喜欢

Deep Learning-based Automated Delineation of Head and Neck Malignant Lesions from PET Images

Hystrix熔断器:服务熔断与服务降级

Pytorch Summary - Automatic gradient

你知道BFD是什么吗?一文详解BFD协议原理及使用场景

Factory mode

阿里云服务器安装配置redis,无法远程访问

Easyexcl export 1million lines of EXECL report font error solution

How to set Google Chrome as the default browser

Automatic 3D Detection and Segmentation of Head and Neck Cancer from MRI Data.

自定义mvc框架实现
随机推荐
MySQL configuring master-slave databases
1.4 regression of machine learning methods
367. 有效的完全平方数-二分法
LSM6DSL之SPI驱动
zabbix4.4配置监控服务器指标,以及图形页乱码解决
五心公益红红娘团队
After installing anaconda, you need to enter a password to start jupyterlab
cenos7下搭建LAMP环境
A comparison of methods for fully automatic segmentation of tumors and involved nodes in PET/CT of h
The 23 most useful elasticsearch search techniques you must know
证券账号开户安全吗?是靠谱的吗?
监控数据源连接池使用情况
请用已学过的知识编写程序,找出小甲鱼藏在下边这个长字符串中的密码,密码的埋藏点符合以下规律:
商业智能BI的未来,如何看待AI+BI这种模式?
UE4 VS的Visual Assist插件设置
1424. diagonal traversal II
Official STM32 chip package download address stm32f10x stm32f40x Download
你必须知道的23个最有用的Elasticseaerch检索技巧
1.4 机器学习方法之回归问题
IDEA自动补全