qiu8310/minapp

<feature request> Page增加watch功能

strange-fish opened this issue · 0 comments

你好,可以考虑增加类似于vue的watch功能吗?
现在也有一些解决方案,但是如果框架能提供支持就更好。
这是我现在解决方案

import { MyPage } from './MyPage'
import { MyComponent } from './MyComponent'

interface CallbackFunction<T = any> {
  (newVal?: T, oldVal?: T): void
}

export type Watch<D = any> = {
  [P in keyof D]: CallbackFunction<D[P]>
}

function observe (obj: Record<string, any>, key: string, watchFun: CallbackFunction) {
  let val = obj[key]
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: true,
    set: function (newVal) {
      if (newVal === val) return
      watchFun(newVal, val)
      val = newVal
    },
    get: function () {
      return val
    }
  })
}

export function watch (ctx: MyPage | MyComponent, obj: Watch) {
  Object.keys(obj).forEach(key => {
    observe(ctx.data, key, function (newVal: any, oldVal: any) {
      obj[key].call(ctx, newVal, oldVal)
    })
  })
}