0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

javascriptのproxyを使って変数の値の変更を検知する。

Posted at

なにがやりたかったか

変数の値の変更を検知して処理を実行したかった。

例 : 変数Aに値が代入されたときに関数Bを実行する。

実現方法

javascriptのproxyを使えば、変数の値がset/getされたときに行う処理を中継できる

実際の動作を見た方が早いのでplaygroudのコードを添付します。

playground

class Test {
    public siteCode: { value: string | undefined };
    constructor() {
        this.siteCode = new Proxy(
            { value: '' },
            {
                // siteCodeに値がsetされた時の処理を中継(proxy)
                set: function (target: any, key: string, value: string | undefined) {
                    if (value) {
                        console.log('setterだよ')
                    }
                    target[key] = value;
                    console.log(target[key])
                    return true;
                },
                // siteCodeの値がgetされた時の処理を中継(proxy)
                get: function (target: any, key: string) {
                    console.log('getterだよ')
                    return target[key];
                },
            }
        );
    }
}

const test = new Test();
console.log(test.siteCode.value) // getterだよ
test.siteCode.value = 'test' // setterだよ
console.log(test.siteCode.value) // getterだよ

公式

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?