flex ComboBox的双向绑定?

时间:2015-06-19 12:11:59

标签: actionscript-3 flex

我有一个集合,我想绑定为ComboBox的数据输入:

private static var LOGOS:ArrayCollection = new ArrayCollection([
 {index:0, label=logo1}, 
 {index:1, label=logo2}
]);

<s:ComboBox selectedItem="@{model.labelIndex}" labelField="@label" dataProvider="{LOGOS}" />

现在,在选择项目时,绑定应该将对象的关联index属性发送到模型并更新labelIndex。 当然,它不能像上面那样工作,因为labelIndex的数据类型与ArrayCollection的数据类型不同。

[Bindable]
private var model:MyModel;

[Bindable]
class MyModel {
   public var:Number labelIndex;
}

问题:如何将数组元素映射到模型,反之亦然?

1 个答案:

答案 0 :(得分:2)

您正在寻找的内容需要一些脚本,绑定并不足以弄清楚如何自行处理。

您可以使用BindingUtils类来定义绑定,并使用chain方法的bindProperty参数来修改值的查找方式。

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/binding/utils/BindingUtils.html

对于combo.selectedItemmodel.labelIndex绑定,您可以将链指定为数组,其中元素定义查找值的路径:

BindingUtils.bindProperty(model, 'labelIndex', combo, ['selectedItem', 'index']);

这将绑定到selectedItem属性,并传递项index属性的值。

另一种方法是有点棘手,需要使用getter函数,该函数根据labelIndex值从数据源中获取对象:

BindingUtils.bindProperty(combo, 'selectedItem', model, {
    name: 'labelIndex',
    getter: function(host:MyModel):Object
    {
        return LOGOS.source.filter(function(item:Object, index:int, array:Array):Boolean
        {
            return item.index === host.labelIndex;
        })[0];
    }
});

这将绑定到labelIndex属性,并且当属性更改时将调用getter函数。该函数将根据模型更改的labelIndex属性值过滤数据源,并返回具有匹配的index属性值的源对象,该属性值最终将为组合框selectedItem属性设置。

您的组合框定义当然需要id才能通过脚本定位

<s:ComboBox id="combo" dataProvider="{LOGOS}" />

请注意,@属性中不需要labelField,这仅适用于需要定位属性的XML数据源。但是,实际上您根本不需要指定此项,因为labellabelField属性的默认值。

相关问题