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

时间:2017-12-22 04:21:31

标签: javascript node.js object watch

我需要通知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这样做或任何调整?

1 个答案:

答案 0 :(得分: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);