qiu8310 / minapp

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

Page 类完整的 OO 支持 #80

Open zaaack opened 6 years ago

zaaack commented 6 years ago

最近又开始写小程序了,发现 minapp 不支持 super 关键字, mixin 不能写到顶层类上, 感觉还是很不方便,于是随手重写了下 pagify, 感觉实现上也没啥问题,不知道为啥 minapp 不支持。


const MixinsKey = '$$$_mixins'
/**
 * mixin lifecycles will always be called even if you override it in subclass
 * @param target
 * @param propertyKey
 * @param descriptor
 */
export function mixin(target: any, propertyKey: PropertyKey, descriptor: PropertyDescriptor) {
  let mixins = target[MixinsKey] = target[MixinsKey] || {}
  Object.defineProperty(mixins, propertyKey, descriptor)
  descriptor.value = (f: any) => f
  return descriptor
}
// Custom pagify with full OO support
export function pagify() {
  return (Ctor: {new(): any}) => {
    let obj = {} as any
    let page = new Ctor()
    let mixins = page[MixinsKey] || {}
    for (const key in page) {
      if (
        typeof page[key] === 'function' &&
        key !== 'constructor'
      ) {
        obj[key] = function(...args: any[]) {
          mixins[key] && mixins[key].apply(this, args)
          return page[key](...args)
        }
      }
    }
    obj.data = page.data
    let _this: any
    let { onLoad } = obj
    obj.onLoad = function (...args: any[]) {
      _this = this
      onLoad.call(this, ...args)
    }
    Object.defineProperty(page, 'data', {
      get() {
        return _this.data
      }
    })
    page.setData = (...args: any[]) => {
      return _this.setData(...args)
    }
    Page(obj)
  }
}
qiu8310 commented 6 years ago

实现方式不一样,不过你这个挺好的

我研究一下看看会不会有些潜在的问题

six006 commented 6 years ago

我直接用的lodash的 _.toPlainObject 解决 super问题