qiu8310 / minapp

重新定义微信小程序的开发
https://qiu8310.github.io/minapp/
927 stars 68 forks source link

<feature request> Page增加watch功能 #106

Closed strange-fish closed 5 years ago

strange-fish commented 5 years ago

你好,可以考虑增加类似于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)
    })
  })
}