无法使用Proxy在customElements上捕获访问器调用?

问题描述 投票:0回答:1

我使用customElements.define注册了一些自定义元素,我想自动设置成员访问器的陷阱,这样当它们发生变化时我就可以发出事件。

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);

我的浏览器似乎没有问题,上面的代码,我可以看到一些陷阱的输出,因为元素设置了

GET trap prototype
GET trap disabledFeatures
GET trap formAssociated
GET trap prototype

但是当我手动设置值时,陷阱并没有被触发,这有可能吗?

javascript proxy custom-element
1个回答
0
投票

我最终做的是将所有成员变量的值移到一个私有对象中,并在自定义元素被挂载到DOM上时为每个变量动态定义一个gettersetter,就像这样......

//
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';

这样一来,我仍然可以像正常的那样在对象上getset值,typescript很高兴成员变量的存在,而且我可以在成员被访问时触发自定义事件--同时允许自定义元素在DOM准备好的标记中存在。

© www.soinside.com 2019 - 2024. All rights reserved.