jerullan
jerullan

Reputation: 57

How to detect a global value change in Node.js

I want to know if there is a way for a client to detect that some global.variable has changed and update the value on the browser whenever the global.variable value changes.

My use case is I have a module that I added to the global object in order to maintain its state across different users requests. Each user can modify a property of this object (global.myobject.myproperty) independently, but I want them to be updated whenever global.myobject.myproperty is modified by any other user.

I'm fairly new to Javascript and Node.js and I'm mostly adventuring into the unknown, so please don't assume I know too much. :)

Any guidance is appreciated.

Upvotes: 3

Views: 3204

Answers (2)

Mulan
Mulan

Reputation: 135217

Here's an approach using 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;

Ok, let's check it out !

// 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!";

Output (check console)

"myproperty changed to: foo!"

Upvotes: 3

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

I don't think its possible, but you could try doing something like:

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'

Upvotes: 0

Related Questions