MXML 类初始化顺序
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
侦听
creationComplete
事件并将组件添加到该事件的处理程序中是实现此目的的一种方法。这是萨姆·德哈恩的建议。另一种方法是重写 createChildren() 函数。这是创建并添加组件的所有子组件的函数。代码如下所示:
有关组件生命周期的文档将提供有关此主题的大量详细信息。
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:The docs on the component lifecycle will provide a ton of detail on this topic.
除非我误解了您的问题,否则
您应该将遇到此空指针异常的代码放在您需要定义的容器上的 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.