How to monitor global variables in WeChat applet

How to monitor global variables in WeChat applet

I recently encountered a problem at work. There is a global variable red_heart. Because it is used in many places, when it changes, the places where it is used must also be changed. However, native applets do not have related practices like Vue. So I want to implement a global variable change myself, and re-render wherever this variable is used.

Get started

First of all, there must be red_heart in the global variable

globalData: {
    red_heart:0,
  },

Then add a Proxy proxy to the global variable in the onLaunch method.

Proxy is easy to understand, and everyone who understands it will understand it.

this.globalData = new Proxy(this.globalData, {
      get(target, key){
        return target[key];
      },
      set:(target, key, value)=>{
        if(key === "red_heart"){
          this.globalDep.RedHeartDep.notify()
        }
        return Reflect.set(target, key, value);
      }
    });

Mainly look at the set method, there is a this.globalDep.RedHeartDep.notify(), what is this. This is a Dep I created globally, short for dependency collection.

Code

globalDep:{
    RedHeartDep:
      subs:[],
      addSub(watch){
        this.subs.push(watch)
      },
      removeWatch(id){
        this.subs = this.subs.filter((item)=>{
          return item.id != id
        })
      },
      notify(){
        setTimeout(()=>{
          this.subs.forEach(w=>w.update())
        },0)
      }
    }
  }

subs is an array used to collect dependencies, addSub and removeWatch, and notification is used to tell this thing to be updated.

Now there is another question, that is, where to add this dependency? Of course, it should be added where it is used, that is, when the component is created.

Attach the full component js code:

const app = getApp()
Component({
  properties:

  },
  data: {
    red_heart:0
  },
  lifetimes:
    attached(){
      let watch = {
        id:this.__wxExparserNodeId__,
        update:()=>{
          this.setData({
            red_heart:app.globalData.red_heart
          })
        }
      }
      app.globalDep.RedHeartDep.addSub(watch)
      app.globalData.red_heart = app.globalData.red_heart
    },
    detached(){
      app.globalDep.RedHeartDep.removeWatch(this.__wxExparserNodeId__)
    }
  },
  methods: {
    handClick(){
      app.globalData.red_heart++
      console.log(app.globalData)
    }
  }
})

Add dependencies to attached, and don't forget to delete the dependencies when the component is destroyed. This id is a compilation id of the mini program and is used directly.
That's it, it's done!

Summarize

This is the end of this article about how WeChat mini programs monitor global variables. For more relevant mini program monitoring global content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to implement WeChat applet global variable change monitoring

<<:  Tutorial on installing MySQL 5.7.18 decompressed version on Windows

>>:  How to open the port in Centos7

Recommend

How to change the domestic source of Ubuntu 20.04 apt

UPD 2020.2.26 Currently Ubuntu 20.04 LTS has not ...

Basic introductory tutorial on MySQL partition tables

Preface In a recent project, we need to save a la...

What are inline elements and block elements?

1. Inline elements only occupy the width of the co...

Detailed explanation of the functions of each port of Tomcat

From the tomcat configuration file, we can see th...

How to install and configure Docker nginx

Download Nginx image in Docker docker pull nginx ...

The front-end must know how to lazy load images (three methods)

Table of contents 1. What is lazy loading? 2. Imp...

Shtml Concise Tutorial

Shtml and asp are similar. In files named shtml, s...

Brief Analysis of MySQL B-Tree Index

B-Tree Index Different storage engines may also u...

How to configure the pdflatex environment in docker

Technical Background Latex is an indispensable to...

Detailed explanation of Xshell common problems and related configurations

This article introduces common problems of Xshell...

Service management of source package installation under Linux

Table of contents 1. Startup management of source...

HTML reuse techniques

HTML reuse is a term that is rarely mentioned. Tod...

Add crontab scheduled tasks to debian docker container

Now most of the Docker images are based on Debian...

A great collection of web standards learning resources

These specifications are designed to allow for bac...

Analysis and summary of the impact of MySQL transactions on efficiency

1. Database transactions will reduce database per...