在Flex中,将字典用作数据提供者的最佳方式是什么?
问题描述:
通常在Flex中,您使用像ArrayCollection这样的集合作为组件的数据提供者。我经常将数据存储为字典,我想将其用作数据提供者的值。在Flex中,将字典用作数据提供者的最佳方式是什么?
你会如何推荐这样做?
答
除了扩展“dataProvider using”组件或创建将使用Dictionary作为源的ListCollectionView类之外,我觉得你有点卡住了。
基于列表的组件设计用于显示某种形式的订单。 Dictionary没有这样的顺序。
答
理想的解决办法是不使用一本字典,但不回答你的问题......
所以,如果你被迫使用字典,来解决这个问题的一个方法是使用一个功能作为你的“中间人”。它可以在字典和Flex组件之间进行切换,这些组件关心什么时候改变。
当然,对于大型字典而言,这可能效率不高,但在大多数情况下,性能应该可以接受。
首先,您需要一个将字典转换为ArrayCollection的函数。之一下列工作实施可能就足够了:
从字典
public function extractKeys(d:Dictionary):ArrayCollection {
var keyList:ArrayCollection = new ArrayCollection();
if(d != null) for(var key:* in d) keyList.addItem(key);
return keyList;
}
public function extractValues(d:Dictionary):ArrayCollection {
var valueList:ArrayCollection = new ArrayCollection();
if(d != null) for each(var value:* in d) valueList.addItem(value);
return valueList;
}
然后提取键/值组合,你实际上可以绑定到这些功能,他们自己!这样,只要底层字典被修改,任何依赖这些函数的对象都会被更新。例如:
使用函数
private var myDictionary:Dictionary; //initialized and used elsewhere
[Bindable(event="dictionaryValueChanged")]
public function extractValues(d:Dictionary):ArrayCollection {
var valueList:ArrayCollection = new ArrayCollection();
if(d != null) for each(var value:* in d) valueList.addItem(value);
return valueList;
}
public function updateDictionary(key:Object, value:Object):void {
myDictionary[key] = value;
dispatchEvent("dictionaryValueChanged");
}
从那里,你可以使用功能为您的数据提供程序绑定到字典中的值。如:
<mx:DataGrid id="valueGrid" dataProvider="{extractValues()}" />
无论何时您的字典更改(通过updateDictionary函数),它最终都会触发DataGrid中的更新!
这实际上只是flex中一个非常强大的技术应用:binding to functions。一旦掌握了它,就可以用这种方法解决各种各样的问题。
我希望帮助别人,
-gMale
编辑:
我不得不玩弄它,但我想你也可以消除通过做一些事情的“updateDictionary”功能像这样,代替:
[Bindable(event="dictionaryValueChanged")]
private var myDictionary:Dictionary; //initialized and used elsewhere
[Bindable(event="dictionaryValueChanged")]
public function extractValues(d:Dictionary):ArrayCollection {
var valueList:ArrayCollection = new ArrayCollection();
if(d != null) for each(var value:* in d) valueList.addItem(value);
return valueList;
}