代码之家  ›  专栏  ›  技术社区  ›  Joshua

相当于使用纯Actionscript的Flex数据绑定

  •  1
  • Joshua  · 技术社区  · 15 年前

    当Flex看到这样的情况时:

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

    它必须以某种方式将其转化为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的情况下实现这一点很重要。

    这样做:

    将不起作用,因为这只是分配一次“{myVar}”的值(它甚至可能不是“stringToBind”中引用的变量!)标签,并且不考虑myVar何时和是否更改!我不需要使用像bindProperty这样的东西吗?

    3 回复  |  直到 15 年前
        1
  •  3
  •   Amarghosh    15 年前

    使用 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的语法。您仍然在内部使用Flex绑定,但是同样地,使用 Label 独自一人,如果 柔性

        2
  •  1
  •   Maxim Kachurovskiy    15 年前
    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 参数,并读取中生成的所有ActionScript bin-debug\generated .

        3
  •  0
  •   qualidafial    12 年前

    揭秘:无耻的自我推销

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

    推荐文章