TS装饰器

发布时间 2023-05-29 20:32:33作者: 00000000O
/**
 * 自动绑定的装饰器
 *
 * @export
 * @param {string} [bindName]
 * @return {*} 
 */
export function autobind(bindName?: string) {
    return function (target: object, properkey: string) {
        bindName = bindName != null ? bindName : (properkey[0] == '_' ? properkey.slice(1, properkey.length) : properkey)
        const getter = function (this: JsProxy) {
            let cache = ensure_has_cache(this)
            if (cache[properkey] != null) return cache[properkey]
            cache[properkey] = this.getBind<any>(bindName)
            return cache[properkey]
        }
        const setter = function (this: JsProxy, newVal: any) {
            throw new Error(`试图对绑定变量${properkey}重新赋值`)
        }
        Object.defineProperty(target, properkey, {
            get: getter,
            set: setter
        })
    }
}

  

 

//Auto-Generated Start
export class LoginPageView extends JsProxy {

    static prefabPath:string = 'Assets/GameRes/Modules/OutSide/Prefabs/UI/Loading/LoginPageView.prefab'

    override get __path(): string {
        return LoginPageView.prefabPath
    }

    @autobind() public bg: RectTransform  

    @autobind() public logo: RectTransform  

    @autobind() public panel: GameObject  

    @autobind() public 8: RectTransform  

    @autobind() public 7: RectTransform  

    @autobind() public 4: RectTransform  

    @autobind() public 13: RectTransform  

    @autobind() public 11: RectTransform  

    @autobind() public 2: RectTransform  

    @autobind() public 3: RectTransform  

    @autobind() public 5: RectTransform  

    @autobind() public 10: RectTransform  

    @autobind() public 9: RectTransform  

    @autobind() public 6: RectTransform  

    @autobind() public 12: RectTransform  

    @autobind() public 1: RectTransform  

    @autobind() public loadBg: GameObject  

}

  

properkey 是被装饰的属性的名称,target 是装饰器被应用的类的构造函数。装饰器用于修改属性的行为,实现自动绑定的功能。

 

装饰器,简单说就是,当修饰对象被调用时,会执行修饰器内函数后的结果

如果一个对象,函数有多个装饰器,那么会嵌套执行装饰器函数后,再执行对象,函数

https://www.tslang.cn/docs/handbook/decorators.html