【问题标题】:Accessing elements in mxml from action script从动作脚本访问 mxml 中的元素
【发布时间】:2013-02-13 05:34:09
【问题描述】:

我有一个如下的 mxml 应用程序。如何从 actionscript 文件中更改标签文本?

<?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="initApp()">
    <fx:Script>
        <![CDATA[
            public function initApp(){
                var p = new my_player("a");
            }
        ]]>
    </fx:Script>
    <s:Label x="700" y="409" text="Label" id="lble" width="131" height="41"/>
</s:Application>

my_player.as 代码

package 
{
    import spark.components.Label;
    public class my_player
    {
        public var lble:Label;
        public function my_player(a:String)
        {
            lble.text="hello";
        }
    }
}

【问题讨论】:

  • 这段代码打破了OOP的基本原则——封装。或者我不明白这个问题。
  • @IlyaZ 怎么会破坏封装原则?
  • 那里有两个 Application 实例,这没有多大意义。如果您之后将 ActionScript 从 MXML 中分离出来,您应该对 Flex 4 (Spark) 蒙皮架构进行一些研究。
  • 在继续这种 mxml 和 as3 分离之前,请查看livedocs.adobe.com/flex/3/html/help.html?content=usingas_6.html
  • @Jari p 对象(第一类)想要链接到标签并在主应用程序中更改标签(第二类)-> 生成新的关系,使将来的修改代码变得困难,这是不好的做法.

标签: actionscript-3 apache-flex mxml flex-spark


【解决方案1】:

使用构造函数将标签从主应用程序注入到传送播放器(另一种方式 - 绑定)

public function initApp(){
    var p = new my_player("a", lble);
}

public function my_player (a:String, targetLabel:Label)
{
    lble = targetLabel;
    lble.text="hello";
}

【讨论】:

    【解决方案2】:

    你不需要第二类:(

    <?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="initApp()">
        <fx:Script>
            <![CDATA[
            public function initApp(){
    
                // access your components by id
                lble.text  = "My new text for the label"
            }
            ]]>
        </fx:Script>
        <s:Label x="700" y="409" text="Label" id="lble" width="131" height="41"/>
    </s:Application>
    

    【讨论】:

    • 我有 4 种类型的流媒体,每种都有单独的类,因为每种都有很多代码,这对我来说不可能全部放在一个 mxml 文件中。
    • 恐怕您使用了错误的方法...我在您的实现中看不到 OOP。请考虑就您想要实现的目标而不是如何解决您遇到的特定问题提供更好的示例或更好的解释
    猜你喜欢
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    相关资源
    最近更新 更多