Using the Bindable metadata tag:
You can use the [Bindable] metadata tag in three places:
1 Before a public class definition.
2 Before a public, protected, or private property defined as a variable to make that specific property support binding.
3 Before a public, protected, or private property defined by a getter or setter method.
The Flex compiler automatically generates an event named propertyChange , of type PropertyChangeEvent, for
the property. If the property value remains the same on a write, Flex does not dispatch the event or update the
property. To determine if the property value changes, Flex calls the getter method to obtain the current value of the
property.
Demo:
DataBase class(单例,用于存储数据)
ActionScript 3语言:
package
{
/**
* This class is use to store the data,
* and test the bindable things in different class
*/
public
class
DataBase
{
private
static
var
_instance
:
DataBase;
public
static
function
get
instance
():
DataBase
{
if (
_instance
==
null)
{
_instance
=
new
DataBase();
}
return
_instance;
}
public
function
DataBase()
{
}
[
Bindable
]
public
var
valueOne
:
Number
[
Bindable
]
public
var
valueTwo
:
Number
}
}
MainApp:
MXML语言:
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx=
"http://ns.adobe.com/mxml/2009"
xmlns:s=
"library://ns.adobe.com/flex/spark"
xmlns:mx=
"library://ns.adobe.com/flex/halo"
minWidth=
"1024"
minHeight=
"768"
>
<fx:Script>
<![CDATA[
private
var
_sliderValue
:
int;
public
function
get
sliderValue
():
int
{
return
_sliderValue;
}
[
Bindable(
event
=
"sliderValueChange"
)]
public
function
set
sliderValue(
v
:
int
):
void
{
_sliderValue
=
v
+
10;
dispatchEvent(
new
Event(
"sliderValueChange"));
}
protected
function
slider_changeHandler(
event
:
Event
):
void
{
sliderValue
=
HSlider(
event
.
target
).
value;
DataBase
.
instance
.
valueOne
=
sliderValue;
}
]]>
</fx:Script>
<s:HSlider
id=
"slider"
x=
"25"
y=
"30"
width=
"158"
height=
"15"
change=
"slider_changeHandler(event)"
/>
<mx:Label
x=
"25"
y=
"60"
text=
"{slider.value}"
textAlign=
"left"
/>
<mx:Label
x=
"25"
y=
"89"
text=
"{sliderValue}"
textAlign=
"left"
/>
<mx:Label
x=
"25"
y=
"117"
text=
"{DataBase.instance.valueOne}"
textAlign=
"left"
/>
<mx:Label
x=
"25"
y=
"143"
text=
"{DataBase.instance.valueTwo}"
/>
<s:layout>
<s:BasicLayout/>
</s:layout>
</s:Application>
在程序中,使用了多种方法对数据进行绑定。
当使用 [Bindable(event="sliderValueChange")] 对数据进行绑定的时候,需要在数据改变时
dispatchEvent(new Event("sliderValueChange"));
否则数据并不发生改变.
最后一个lable 虽然对DataBase.instance.valueTwo进行了数据绑定,但是由于valueTwo的值从没改变过,所以
text绑定后的显示值一直不会改变。
使用get、set函数进行绑定时 需要将 [Bindable(event="sliderValueChange")] 绑定参数 写在set函数之前而非get函数之前.