当前位置:网站首页>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 .
边栏推荐
- Gd32f4xx Ethernet Chip (ENC28J60) Drive transplantation
- 監控數據源連接池使用情况
- 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:
- 基于stm32标准库独立按键的多按键状态机的实现
- mysql修改自动递增初始值
- Pytorch learning summary - memory cost of operation
- 长安链GO语言智能合约编写与编译
- Segmentation of Head and Neck Tumours Using Modified U-net
- 数据可视化:数据可视化的意义
- Fully Automated Delineation of Gross Tumor Volume for Head and Neck Cancer on PET-CT Using Deep Lear
猜你喜欢

Factory mode

zabbix4.4配置监控服务器指标,以及图形页乱码解决

linux环境下安装配置redis,并设置开机自启动

Gd32f4xx Ethernet Chip (ENC28J60) Drive transplantation

Reading notes on how to connect the network - Web server request and response (IV)

遍历vector容器中的对象的方式

基于keil5自动配置stm32f103标准库的官网freertos移植

Making of simple addition calculator based on pyqt5 and QT Designer

Visual assist plug-in settings for UE4 vs

Segmentation of Head and Neck Tumours Using Modified U-net
随机推荐
Pytorch summary learning series - broadcast mechanism
UE4 material UV texture does not stretch with model scale
Segmentation of Head and Neck Tumours Using Modified U-net
C # judge whether the array contains any items of another array
Deep Learning-based Automated Delineation of Head and Neck Malignant Lesions from PET Images
阿里云服务器安装配置redis,无法远程访问
[Huawei certification] the most complete and selected question bank in hcia-datacom history (with answer analysis)
The former security director of Uber faced fraud allegations and had concealed data leakage incidents
长安链数据存储介绍及Mysql存储环境搭建
UE4 材质UV纹理不随模型缩放拉伸
LeetCode刷题——泰波那契数列
ORA-01950 对表空间无权限
A 3D Dual Path U-Net of Cancer Segmentation Based on MRI
The principle of session and cookie
Pytorch Summary - Automatic gradient
Deep Learning-based Automated Delineation of Head and Neck Malignant Lesions from PET Images
Segmentation of Head and Neck Tumours Using Modified U-net
用户级线程和内核级线程
数据可视化:数据可视化的意义
Automatic Multi-Organ SegmVentation on Abdominal CT With Dense V-Networks