我想知道客户端是否有办法检测到某些global.variable已更改并在global.variable值更改时更新浏览器上的值。
我的用例是我有一个模块,我添加到全局对象,以便在不同的用户请求中维护其状态。每个用户可以独立修改此对象的属性(global.myobject.myproperty),但我希望每当任何其他用户修改global.myobject.myproperty时都会更新它们。
我对Javascript和Node.js相当陌生,我主要是冒险进入未知世界,所以请不要认为我知道的太多了。 :)
感谢任何指导。
答案 0 :(得分:3)
这是使用EventEmitter
的方法var EE = require("events").EventEmitter;
function MyObject() {
// call EE constructor
EE.call(this);
// myProperty instance variable
var myProperty;
// define dynamic property
Object.defineProperty(this, "myproperty", {
get: function() {
return myProperty;
},
set: function(newValue) {
myProperty = newValue;
this.emit("change:myproperty", myProperty);
return myProperty;
}.bind(this)
});
}
// setup prototype
MyObject.prototype = EE.prototype;
MyObject.prototype.constructor = MyObject;
好的,我们来看看吧!
// create an instance of your object
var obj = new MyObject();
// listen for changes
obj.on("change:myproperty", function(myproperty) {
console.log("myproperty changed to:", myproperty);
});
// change the property
obj.myproperty = "foo!";
输出(检查控制台)
"myproperty changed to: foo!"
答案 1 :(得分:0)
我不认为这是可能的,但你可以尝试做类似的事情:
var ev = require('events');
var someString = function(val) {
this.myVal = val;
//change function for string
this.change = function(newVal) {
//check for newVal
if( this.myVal != newVal ) {
//assign the new value
this.myVal = newVal;
//emit the changed event
this.emit('changed');
}
}
this.val = function() {
return this.myVal;
}
};
//Copy EventEmitter properties to the someString object
someString.prototype.__proto__ = events.EventEmitter.prototype;
var doSomething = function(){
console.log('string changed');
};
var somestring = new someString('');
console.log(somestring.val()); // outputs ''
somestring.on('changed',doSomething);
somestring.change('testing'); //outputs 'string changed'
console.log(somestring.val()); //outputs 'testing'