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

Installing Win10 system on VMware workstation 14 pro

This article introduces how to install the system...

How to set Tomcat as an automatically started service? The quickest way

Set Tomcat to automatically start the service: I ...

Docker View Process, Memory, and Cup Consumption

Docker view process, memory, cup consumption Star...

About scroll bar in HTML/removing scroll bar

1. The color of the scroll bar under xhtml In the ...

CSS to achieve Cyberpunk 2077 style visual effects in a few steps

background Before starting the article, let’s bri...

Detailed steps to install RabbitMQ in docker

Table of contents 1. Find the mirror 2. Download ...

Examples of using MySQL covering indexes

What is a covering index? Creating an index that ...

Example of how to set automatic creation time and modification time in mysql

This article describes how to set the automatic c...

Monitor the size change of a DOM element through iframe

A common problem encountered during the developme...

How to add vim implementation code examples in power shell

1. Go to Vim's official website to download t...

MySQL 8.0.21 installation tutorial with pictures and text

1. Download the download link Click download. You...

Basic introductory tutorial on MySQL partition tables

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

How to find and delete duplicate records in MySQL

Hello everyone, I am Tony, a teacher who only tal...

Three ways to achieve background blur in CSS3 (summary)

1. Normal background blur Code: <Style> htm...