Internal setter with public getter doesn't work
I have a problem whereby in AS3 using Flash Builder 4 using a public getter with an internal setter gives me the error "property is read only", l开发者_如何学Pythonike so:
public function get aVar():int{ return _aVar; }
internal function set aVar(value:int):void { this._aVar = value; }
I have used a workaround of:
public function get aVar():int{ return _aVar; }
internal function setAVar(value:int):void { this._aVar = value; }
This seems to be a bug in AS3, or maybe I am missing something? Does anyone know of a better workaround?
Thanks
Getter and Setter must have the same access type, that's not a bug.
As far as I know the getter and setter must be identical, so either both public or both internal.
I'm currently having trouble finding the docs to back this up, although I have had similar error in the past when trying to mix public and private.
The issue has come up before and I have already mentioned the workaround in my blog. The problem lies with how binding works in Flex since it needs to compare values before a binding event is dispatched (by default). The workaround is easy enough however, but slightly annoying because of the extra code:
// Internal Variable
private var __state:String = "someState";
// Bindable read-only property
[Bindable(event="stateChanged")]
public function get state():String
{
return this._state;
}
// Internal Getter-Setter
protected function get _state():String
{
return this._state;
}
protected function set _state(value:String):void
{
this.__state = value;
dispatchEvent(new Event("stateChanged"));
}
Since there is no overloading in AS3, one cannot have any ambiguity in terms of name spaces. Accessors are treated as properties, so, as any property, it cannot be both protected and public. In your case solution, perhaps, is to make the variable accessors designed to handle protected (or internal), while getter - public (and no setter).
// getter is publilc and setter is internal
public string EmployeeCode
{
// getter is publilc and setter is internal
public string EmployeeCode
{
get
{
return _employeeCode;
}
internal set
{
_employeeCode = value;
}
}
}
There is one thing to keep remember is that you cannot specify access modifier for both getter and setter at same time. The other will always take the default from property. However this doesn’t matter to us as we can achieve any combination from available flexibility.
精彩评论