第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法使用代理在自定義元素上捕獲訪問器調(diào)用?

無法使用代理在自定義元素上捕獲訪問器調(diào)用?

慕俠2389804 2022-09-16 21:08:36
我正在使用 customElements.define 注冊一些自定義元素,并希望在成員訪問器上自動設(shè)置陷阱,以便在事件更改時發(fā)出事件class State extends HTMLElement {    public someValue = 1;    public constructor() {        super();        console.log('State constructor');    }}const oProxy = new Proxy(State, {    get(target, prop: string) {        console.log(`GET trap ${prop}`);        return Reflect.get(target, prop);    },    set(target, prop: string, value: any) {        console.log(`SET trap ${prop}`);        return Reflect.set(target, prop, value);    }});customElements.define('my-state', oProxy);const oStateEl = document.querySelector('my-state');console.log(oStateEl.someValue);console.log(oStateEl.someValue = 2);console.log(oStateEl.someValue);我的瀏覽器似乎沒有上述代碼的問題,我可以看到一些陷阱輸出,因為元素已設(shè)置GET trap prototypeGET trap disabledFeaturesGET trap formAssociatedGET trap prototype但是,當(dāng)我手動獲取/設(shè)置值時,陷阱不會被觸發(fā)。這有可能嗎?
查看完整描述

1 回答

?
慕尼黑的夜晚無繁華

TA貢獻(xiàn)1864條經(jīng)驗 獲得超6個贊

我最終所做的是將所有成員變量值移動到一個私有對象,并在自定義元素掛載到DOM上后立即為每個對象動態(tài)定義一個 getter/setter,如下所示...


//

class State extends HTMLElement {


    protected _data: object = {}


    public connectedCallback() {

        // Loop over member vars

        Object.getOwnPropertyNames(this).forEach(sPropertyKey => {

            // Ignore private

            if(sPropertyKey.startsWith('_')) {

                return;

            }


            // Copy member var to data object

            Reflect.set(this._data, sPropertyKey, Reflect.get(this, sPropertyKey));


            // Remove member var

            Reflect.deleteProperty(this, sPropertyKey);


            // Define getter/setter to access data object

            Object.defineProperty(this, sPropertyKey, {

                set: function(mValue: any) {

                    console.log(`setting ${sPropertyKey}`);

                    Reflect.set(this._data, sPropertyKey, mValue);

                },


                get: function() {

                    return this._data[sPropertyKey];

                }

            });

        });

    }


}


// 

class SubState extends State {


    public foobar = 'foobar_val';

    public flipflop = 'flipflop_val';


    public SubStateMethod() { }


}


//

window.customElements.define('sub-state', SubState);


//

const oState = document.querySelector('sub-state') as SubState;

oState.foobar = 'foobar_new_val';

這樣,我仍然可以像往常一樣獲取/設(shè)置對象的值,typescript很高興成員變量存在,并且我可以在訪問成員時觸發(fā)自定義事件 - 同時允許自定義元素存在于DOM就緒的標(biāo)記中。


查看完整回答
反對 回復(fù) 2022-09-16
  • 1 回答
  • 0 關(guān)注
  • 110 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號