In Sproutcore i am using the universal setter/getter method like so:
foo.set('bar', newValue );
val = foo.get('bar');
This is quite different to Objective-c, how would i write a custom ge开发者_JS百科tter/ setter?
EDIT
Thanks to those who helped, the way to do it is
bar: function( propKey, propVal ) {
if(propVal===undefined) { // called as getter method
var computedBarValue = ...
return computedBarValue;
} else {
this.bar = propVal + ... // called as setter method
}
}.property()
As you can see, you have one method that is the both the getter and the setter.
if you call
val = foo.get('bar');
the method argument 'propVal' will be undefined.
if you call
foo.set('bar', newValue );
the method argument 'propVal' will be newValue
Custom setter/getter function would look smth like this:
bar: function(key, value){
if(value != undefined){
this._bar = value;
}
return this._bar;
}
This would simply get/set the value. To do smth on set, just add what you want after this._bar = value, to do smth on get, just add if value == undefined.
精彩评论