2011-02-17 52 views
1

我已经创建了一个基于Image组件的自定义组件。我想教它回应绑定变量的变化。例如。如果主类有一个可变余额,我希望组件在图片余额= 100的情况下更改图片,如果余额= 50到另一图片。flex:如何响应组件内部的数据更改

有人可以帮助了解如何做到这一点


我使用flex3所以看不到propertyWatcner那里。另外我使用COMPONENT2从主MXML文件这样

<MyComp:MyIcon left="15" top="20" width="60" height="60" 
    id="tower" price="100" accountState="{accountMoney}" 
    click="drawBuildingShadow(event)" /> 

和组件MyIcon里面我希望能够作出反应绑定accountState变量的变化。

+0

您可以将变量转换为getter/setter并更改setter中的图片。 – alxx 2011-02-18 19:32:21

回答

3

没有任何代码可以通过(请包括这两个组件的样本,如果可以的话),有很多方法可以解决这个问题。

您可以添加绑定到所讨论变量的ChangeWatcher,并在属性更改时调用方法。此方法可以根据适用于属性的任何条件来更改图像。

它看起来东西这样的:

Component 1: 
    [Bindable] 
    public var yourVariable:Number; 

Component 2: 
    private var propertyWatcher:ChangeWatcher; 
    //In some initialization method -- this is JUST an example method for how to create the property watcher 
    public function init(): void { 
     ... 
     propertyWatcher = ChangeWatcher.watch(component1, "yourVariable", onVariableUpdate); 
    } 

    //Define this as a new method to handle when the property changes 
    private function onVariableUpdate(event:PropertyChangeEvent):void { 
    if(event.newValue == 50) { 
     yourImage.source = newSource; 
    } 
    else if(event.newValue == 100) { 
     yourImage.source = otherSource; 
    } 
    } 

显然,这是非常截断和速记,但希望它会帮助你开始。


编辑:ChangeWatchers确实存在Flex 3中,但它听起来像是你应该在不同的方向走。由于您发布的代码片段有点小,因此我将对如何执行此操作做一些假设:)

正如alxx在他的评论中提到的,您可以将组件中的属性accountState更改为实际的财产,给一个setter/getter。这将允许您在accountState更新时进行更广泛的处理。

它看起来应该东西这样的:

MyComp:

//Inside your script tag: 
private var _accountState:Number; 

[Bindable] 
public function get accountState():Number { 
    return _accountState; 
} 
public function set accountState(state:Number):void { 
    _accountState = state; 
    switch(state) { 
     case 50: 
      yourIcon.source = "blahblahblah"; 
      break; 
     case 100: 
      yourIcon.source = "blahblahblah2"; 
      break; 
     //And so on 
    } 
} 

这不会更改您发布的代码:它应该仍然工作作为你写它。我没有测试过,所以有可能我失去了一些东西,但希望这会有所帮助:)

+0

请参阅评论 – 2011-02-18 18:04:24