【问题标题】:Equivalent of Flex DataBinding using Pure Actionscript使用 Pure Actionscript 的 Flex DataBinding 等效项
【发布时间】:2010-06-14 05:13:20
【问题描述】:

当 Flex 看到这样的事情时:

<mx:Label text="Hello {MyVar} World!"/>

它必须以某种方式将其转换为 ActionScript。但是如果我需要在运行时做类似的事情怎么办。我怎样才能动态地完成什么?当我不知道绑定模板的内容时。

在 ActionScript 中,它需要它看起来像这样某种东西

public function CustomDynamicBinding(StringToBind:String):Label {
  // *EXAMPLES* Of StringToBind:
  //    "Hello {MyVar} World!"
  //    "Product: {name} ${price}.00"
  //    "{data.label}, {data.description}"
  // I've Written It This Way Because I DO NOT KNOW The Exact Text To Be Bound At Design Time.
  [Bindable]
    var Lab:Label=new Label();
    Lab.text=???
    return(Lab);
}

我怎样才能完成这种“动态”绑定...直到运行时我才不知道“StringToBind”的值?出于这个问题的目的,我们可以假设我确实知道“StringToBind”中提到的任何变量都保证在运行时存在。

我已经意识到有更直接的方法可以静态地完成这个确切的事情,并且只使用 Flex/MXML。这对我的项目很重要,但我了解如何在没有 MXML 的情况下实现这一点。

这样做: lab.text = stringToBind.replace("{myVar}", str);

将不起作用,因为这只是将“{myVar}”的值(甚至可能不是“stringToBind”中引用的变量!!)分配给标签,并且不考虑何时以及是否 myVar变化!我不需要以某种方式使用 bindProperty 之类的东西吗?

【问题讨论】:

标签: apache-flex flash actionscript-3 actionscript air


【解决方案1】:

使用BindingUtils.bindSetter

var stringToBind:String = "Hello {myVar} World!";
[Bindable]
var myVar:String = 'Flex';
var lab:Label = new Label();
BindingUtils.bindSetter(labelValue, this, "myVar");
function set labelValue(str:String):void
{
  lab.text = "Hello " + str + " World!";
  //or if you want it dynamic
  lab.text = stringToBind.replace("{myVar}", str);
}

请注意,这并不是严格意义上的纯 ActionScript,因为数据绑定本身是一个 Flex 概念;这只是做它的 MXML-less 语法。您仍在内部使用 Flex 绑定 - 但同样,单独使用 Label 会使 if Flexy

【讨论】:

  • 您已经硬编码了“StringToBind”。整个要点是在设计时不知道绑定的内容。
  • 如果这样做,标签文本在 myVar 更改时也不会更改。
  • @Joshua 你试过这个吗?标签文本会随着myVar 的变化而变化。关于硬编码 - 这不像&lt;mx:Label text="Hello {MyVar} World!"/&gt; 硬编码那样硬编码。你可以随时在运行时更新stringToBind 并使用我的第二种方法。
  • @Joshua 你没抓住重点。关键是使用 bindSetter 设置一个函数,当您选择的属性值发生变化时该函数将执行。无论您在该功能中做什么都取决于您。
【解决方案2】:
private function _BindingSource_bindingsSetup():Array
{
    var result:Array = [];

    result[0] = new mx.binding.Binding(this,
        function():String
        {
            var result:* = "Hello " + (MyVar) + " World!";
            return (result == undefined ? null : String(result));
        },
        null,
        "_BindingSource_Label1.text"
        );


    return result;
}

这只是生成代码的一部分。随意将-keep-generated-actionscript 参数添加到编译器选项并阅读bin-debug\generated 中所有生成的ActionScript。

【讨论】:

  • 你已经硬编码了“Hello World”和“MyVar”...这对我有什么帮助?
【解决方案3】:

披露:无耻的自我宣传

BindageTools 库提供了一个直观的构建器 API,用于在 ActionScript 中设置绑定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多