在 Flex 中创建子组件之前初始化自定义组件的属性
假设我有以下自定义组件:
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
[Bindable]
public var prop:String;
private function formatProp() : String {
return "Hello, " + prop;
}
]]>
</fx:Script>
<s:Label text="User: {prop}"/>
<s:Label text="Greeting: {formatProp()}"/>
</s:Group>
如果我将其添加到我的应用程序中,如下所示:
<local:MyComponent prop="Hello"/>
结果如下所示:
User: Mark Greeting: Hello, null
Flex 似乎在初始化子标签后在我的自定义组件上设置 prop
,因此它依赖于属性更改事件来设置用户标签。
有没有一种优雅的方法可以让 Flex 在最初评估绑定之前等待设置所有组件的属性?
注意:我意识到 formatProp 函数很简单,可以内联包含,但这只是一个简化的示例。
Say I have the following custom component:
<s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
[Bindable]
public var prop:String;
private function formatProp() : String {
return "Hello, " + prop;
}
]]>
</fx:Script>
<s:Label text="User: {prop}"/>
<s:Label text="Greeting: {formatProp()}"/>
</s:Group>
If I add it to my application like this:
<local:MyComponent prop="Hello"/>
The result looks like:
User: Mark Greeting: Hello, null
It seems Flex is setting prop
on my custom component after it has already initialized the child labels, so it's reliant on the property changed event to set the user label.
Is there an elegant way to make Flex wait for all of my component's properties to be set before initially evaluating bindings?
Note: I realize the formatProp function is trivial and could be included inline, but this is just a simplified example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“优雅的方式”是实际提供数据绑定,以便您之后也可以更改属性。根据康奈尔提供的答案,您最初的想法看起来不错。我只是想提一下这一点,因为您的实际问题听起来更像是您知道数据绑定不起作用,而您只是想推迟变量的初始设置。
顺便说一句,如果您计划在 Actionscript(而不是 mxml)中创建自定义组件,您将面临相反的问题:属性是在您有机会实际创建子组件之前设置的,因此如果它们实际上应该影响,您可能需要缓冲它们一些孩子的财产。
The "elegant way" would be to actually provide data binding, so that you can change your property also afterwards. Your initial idea looked good, working with the answer provided by Cornel. I just wanted to mention this as your actual question sounded more like that you know your data binding is not working and you just wanted to postpone the initial setting of the variable.
Btw, should you plan to create custom components in Actionscript (instead of mxml) you'll face the opposite problem: properties are set before you had a chance to actually create your children, so you may need to buffer them if they actually should influence some childs properties.
它与组件生命周期无关,更多与绑定规则有关。您的函数“formatProp”应该接收参数“prop”作为参数,以便在 prop 更改时被调用。试试这个代码:
it is not related to component livecycle, more to binding rules. Your function "formatProp" should recieve the parameter "prop" as a parameter in order to be called when the prop is changed. Try this code: