Open
Description
最近又开始写小程序了,发现 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)
}
}