Javascript – attach get/set function to objects property in js

bindingjavascriptoop

I essentially have an object:

var foo = function() {
  this.setting = false;
  this.refresh = function() { ... };
}

let a = new foo();
a.setting = true; // a.refresh() is triggered

I need to trigger refresh anytime .setting is written to. I feel like it has something to do with bind, but I couldn't quite get it.

Best Answer

You could use JavaScript getters and setters. See the MDC documentation on the subject and John Resig's blog post on the subject. Note that not all browsers support this.

var Foo = function()//constructor
{
   this._settings = false;//hidden variable by convention
   this.__defineGetter__("settings", function(){
     return _settings;//now foo.settings will give you the value in the hidden var
   });

   this.__defineSetter__("settings", function(s){
      _settings = s;//set the hidden var with foo.settings = x
      this.refresh();//trigger refresh when that happens
   });

   this.refresh = function(){
      alert("Refreshed!");//for testing
   }
}

var a = new Foo();//create new object
a.settings = true;//change the property
//a.refresh() is triggered

Try it!