MXML 类初始化顺序

发布于 2024-11-28 01:55:15 字数 426 浏览 1 评论 0原文

我在 Flex 4 中编写了一些自定义组件,并多次遇到此问题。

var myForm:MyForm = new MyForm;
myForm.SetData(data);
addElement(myForm);

现在想象一下,我从面板或 VGroup(或任何其他容器)的非构造函数调用这些函数。令人烦恼的是,在 MyForm.SetData() 期间,并非所有声明的 myForm 字段都已初始化。例如:

<s:VGroup id="dataGroup">

如果我的 SetData() 函数想要访问 dataGroup(因为要 .addElement() 刚刚收到的数据),它就会失败并出现空指针异常,因为 dataGroup 尚未创建,尽管这是在之后构造函数。如何保证表单已完全初始化?

I have written a few custom components in Flex 4, and run into this issue a few times.

var myForm:MyForm = new MyForm;
myForm.SetData(data);
addElement(myForm);

Now Imagine I am calling these functions from a non-constructor function of a Panel or VGroup (or any other container). Annoyingly, during MyForm.SetData(), not all fields of myForm that are declared there are yet initialized. Such as:

<s:VGroup id="dataGroup">

If my SetData()-function wants to access dataGroup (for the reason to .addElement() the just recieved data to it), it just fails with a nullpointer exception, because dataGroup is not yet created, despite this being after the constructor. How can guarantee that the form was initialized fully?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稀香 2024-12-05 01:55:15

侦听 creationComplete 事件并将组件添加到该事件的处理程序中是实现此目的的一种方法。这是萨姆·德哈恩的建议。

另一种方法是重写 createChildren() 函数。这是创建并添加组件的所有子组件的函数。代码如下所示:

override public function createChildren():void
{
    super.createChildren();

    var myForm:MyForm = new MyForm;
    // Note that data may be null here, best to 
    // override commitProperties() to set it.
    myForm.SetData(data);   
    addElement(myForm);
}

有关组件生命周期的文档将提供有关此主题的大量详细信息。

Listening for the creationComplete event and adding your components in the handler for the event is one way to do this. This is what Sam DeHaan suggested.

Another way you can do this is to override the createChildren() function. This is the function that creates and adds all of a component's child components. Code would look something like this:

override public function createChildren():void
{
    super.createChildren();

    var myForm:MyForm = new MyForm;
    // Note that data may be null here, best to 
    // override commitProperties() to set it.
    myForm.SetData(data);   
    addElement(myForm);
}

The docs on the component lifecycle will provide a ton of detail on this topic.

〃安静 2024-12-05 01:55:15

除非我误解了您的问题,否则

您应该将遇到此空指针异常的代码放在您需要定义的容器上的 creationComplete 回调中。

Unless I'm misunderstanding your question,

You should put the code that runs into this null pointer exception in a creationComplete callback on the container that you need defined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文