Flex: Help me understand the data. Binding to getters and setters.

Help me understand the data linking
When I create a variable in the class:

[Bindable] private var _name: String;

and then generate getters and setters, I get:

private var _name:String; [Bindable] public function get name():String { return _name; } public function set name(value:String):void { _name = value; } 

Why does it generate the '[Bindable]' tag only in the get function?
It seems to me that this should be on a given function, since I would like to know when the value changes, and not when the value has just been read.

+4
source share
1 answer

What can help you understand what is happening here is the code that the MXML compiler will generate for you when you do [Bindable]. The MXML compiler wraps your [Bindable] property in its own getter / setter. It does this so that the wrapper setting method can dispatch the propertyChange event when a new value is set. This event notifies parties associated with this property that the value has changed.

Getters / setters in ActionScript are considered object properties (they are not object methods). Therefore, it doesn't matter if your annotating getter or setter adds as [Bindable], the generated code does the right thing.

It is worth noting that you can avoid the generated code and optimize the situation by sending your own event when your property changes. To do this, the [Bindable] metadata tag must include the name of the event that will be sent when the property changes:

 private var _name:String; [Bindable("nameChanged")] public function get name():String { return _name; } public function set name(value:String) { if (_name == value) return; _name = value; dispatchEvent(new Event("nameChanged")); } 

Because binding metadata contains an event string, no additional code is generated. Please note that the compiler will not warn you if you forget to send an event from the setter. In fact, you can send your custom binding event from anywhere in your class (this can be useful with functions that can be linked).

+12
source

Source: https://habr.com/ru/post/1482023/


All Articles