Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attach get/set function to objects property in js

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.

like image 785
ben Avatar asked Apr 12 '11 22:04

ben


3 Answers

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!

like image 150
Adam Avatar answered Sep 21 '22 14:09

Adam


You need to use a getter and a setter for your object. One way is to use getter/setter functions directly:

var foo = function()
{
   this.setting = false;
   this.getSetting = function() { return this.setting; }
   this.setSetting = function(val) { this.setting = val; this.refresh(); }
   this.refresh = function()
   {...}
}

If you want to use foo.setting transparently as an attribute, there are language constructs for that, but unfortunately they are not interoperable across browsers. In somewhat of a throwback to 3 years ago, there's one method supported by Mozilla, Safari, Chrome and Opera and another method for Internet Explorer. This is the standard method:

http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/

IE9 has something else, and I'm not sure if it even works for non-DOM objects.

like image 40
Boaz Yaniv Avatar answered Sep 21 '22 14:09

Boaz Yaniv


Are you looking for a setting setter? Something like this?

// renamed settings property with underscore
this._settings = false;

this.settings = function(s) {
     if(s !== undefined) {
        this._settings = s;
        this.refresh();
     }

     return this._settings;
};

...


var f = new foo();
f.setSettings(mySettings);

I tend to combine my getter and setter into one method in JavaScript since it's so easy to do. The downside to this is _settings is still public on your object and anyone can directly write to it. The only way to hide it is to use a closure, which requires a totally different approach to creating your objects.

like image 26
Matt Greer Avatar answered Sep 20 '22 14:09

Matt Greer