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.
I don't why you are trying to use the "new" operator, you will be better using the object literal. Now, if you are looking similar to, let's say, C# properties, you could do something like this:
For more info, I recommend this: http://www.crockford.com/javascript/private.html
Are you looking for a setting setter? Something like this?
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.You need to use a getter and a setter for your object. One way is to use getter/setter functions directly:
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.
I know this is an old question that has already been answered, but I'd like to provide a solution that takes advantage of JavaScript's latest syntax.
Define a class with a getter and setter:
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.
Try it!
If you aren't limited with old browsers you may try to use the approach described here