我在我的flex项目中使用MVC模型。
我想要的是将值对象的类属性绑定到视图mxml,然后通过更改值对象来更改该视图。
会发生什么:
为什么只有第一次更新有效?我知道我可能错过了一些明显的东西......
(P.S。第一篇文章,我不知道如何打开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/mx"
creationComplete="created(event)"
width="160" height="220">
<fx:Script>
<![CDATA[
import mx.collections.ArrayList;
import mx.events.FlexEvent;
import spark.events.IndexChangeEvent;
//===================================
// Pretend Value Object Class
[Bindable] private var list:ArrayList = null;
[Bindable] private var index:int = 0;
//===================================
protected function created(event:FlexEvent):void {
ddValues.addEventListener(FlexEvent.ENTER, update);
update();
}
private function update(... args):void {
//note selected item
trace("dropdown index: " + dd.selectedIndex);
var s:String = dd.selectedItem as String;
trace("selected item: " + s);
//build new list from csv
list = new ArrayList(ddValues.text.split(","));
trace("new list: " + ddValues.text);
trace("selected item: " + s);
//if exists in new list, set value object index
var newIndex:int = 0;
if(list)
list.toArray().forEach(function(ss:String, i:int, a:Array):void {
if(s == ss) newIndex = i;;
});
index = newIndex;
trace("new index: " + index + " (dropdown index: " + dd.selectedIndex + ")");
trace("===");
}
protected function ddChange(event:IndexChangeEvent):void
{
trace("selected item: " + (dd.selectedItem as String) + " (dropdown index: " + dd.selectedIndex + ")");
trace("===");
}
]]>
</fx:Script>
<s:Panel width="100%" height="100%" title="Drop Down Bug">
<s:layout>
<s:VerticalLayout gap="10" paddingLeft="10" paddingTop="10" paddingRight="10" paddingBottom="10"/>
</s:layout>
<s:DropDownList id="dd" dataProvider="{list}" selectedIndex="@{index}" change="ddChange(event)"></s:DropDownList>
<s:Label text="Label: {dd.selectedItem as String}" paddingTop="5" paddingBottom="5"/>
<s:Label text="Code Index: {index}" paddingTop="5" paddingBottom="5"/>
<s:Label text="DropDown Index: {dd.selectedIndex}" paddingTop="5" paddingBottom="5"/>
<s:TextInput id="ddValues" text="a,b,c,d,e"/>
</s:Panel>
</s:Application>
继续输出 编辑代码并添加跟踪。下面是显示我问题的输出:
dropdown index: -1
selected item: null
new list: a,b,c,d,e
selected item: null
new index: 0 (dropdown index: 0)
===
selected item: c (dropdown index: 2)
===
dropdown index: 2
selected item: c
new list: a,b,x,y,z,c,d,e
selected item: c
new index: 5 (dropdown index: 5)
===
dropdown index: 5
selected item: c
new list: a,b,x,y,z,c,d,e
selected item: c
new index: 5 (dropdown index: 5)
===
dropdown index: -1
selected item: null
new list: a,b,x,y,z,c,d,e
selected item: null
new index: 0 (dropdown index: 0)
===
答案 0 :(得分:0)
哦,我知道现在发生了什么。当您替换整个列表时,所选项将为空,因为所选项目位于旧列表中。选择后,您需要存储所选项目,然后对存储的项目进行比较,而不是当前选定的(空)项目。
请注意,除非您将MVC重新定义为“模型,视图和控制器完全相同”,否则您所做的事情绝不是MVC。在MVC中,模型不知道视图,并且视图只能访问 read 以及显示数据所需的模型。它没有写访问模型的权限。这是控制器的功能。