在Node.js中观察对象中的变量

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

我需要通知Object中一些变量的变化。但Object不是预定义的。我试过下面的Watchers

watchjs

watchObject

gawk

在所有这些观察者中,Object是预定义的。

我需要一个像下面这样的功能。

//Initially the Object will be empty.
var ex1 = {      
};

//Will watch for variable1 in that Object
watch(ex1, "variable1", function(){
    console.log("Variable1 changed");
});

//Changing or Adding a variable1 in Object. Now the above watch should trigger.
ex1 = {
    variable1 : "Hai",
    variable2 : "Hello"
}

任何Watchers这样做或任何调整?

javascript node.js object watch
1个回答
0
投票

发布在下面,因为它可能会帮助一些像我这样的人。

我通过使用assign实现了这一点。

//Initially the Object will be empty.
var ex1 = {      
};

//Will watch for variable1 in that Object
watch(ex1, "variable1", function(){
    console.log("Variable1 changed");
});

//Changing or Adding a variable1 in Object. Now the above watch got triggered.
var ex2 = {
    variable1 : "Hai",
    variable2 : "Hello"
}

Object.assign(ex1, ex2);
© www.soinside.com 2019 - 2024. All rights reserved.