I recently had a problem with my work. There is a global variable red_heart, because it is used in many places, and when it changes, so does where it is used. But native applets don’t have the same approach as Vue. So I decided to implement a global variable change myself and re-render where I used it.

Let’s start

First of all, the global variable must have this red_heart first

globalData: {
    red_heart:0,
  },
Copy the code

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

  • Proxy is very easy to understand, understand.
this.globalData = new Proxy(this.globalData, { get(target, key){ return target[key]; }, set:(target, key, value)=>{ if(key === "red_heart"){ this.globalDep.RedHeartDep.notifuy() } return Reflect.set(target, key, value); }});Copy the code

See if there is a set method mainly enclosing globalDep. RedHeartDep. Notifuy (), and this is what. This is a Dep, or dependency collection, that I created globally. code

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

Subs is an array that collects dependencies, addSub, and removeWatch, and notifuy is used to tell the thing to update.

Now there is a question of where the dependency is added, where it is used, 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)
    }
  }
})
Copy the code

Add dependencies to attached files and don’t forget to remove dependencies during component destruction. This id is a compilation ID of the applet and is used directly.

Harm is done like this!

The plane!