为什么 MXML 数据绑定会吞下 TypeErrors? [英] Why does MXML data binding swallow TypeErrors?
问题描述
以下代码应该抛出一个错误#1009:无法访问空对象引用的属性或方法
:
The following code shoud throw an Error #1009: Cannot access a property or method of a null object reference
:
var label:Label;
label.text = value;
但是,如果它位于由 MXML 数据绑定设置的 setter 内部,则不会:
However, it doesn't if it's inside of a setter which is set by MXML data binding:
public function set buggySetter(value:String):void {
var label:Label;
label.text = value; //will fail silently
}
要重现这种奇怪的行为,首先,通过扩展 s:Label 创建一个简单的自定义组件:
To reproduce this weird behaviour, first, create a simple custom component by extending s:Label:
package {
import spark.components.Label;
public class BuggyLabel extends Label {
public function set buggySetter(value:String):void {
var label:Label;
label.text = value; //will fail silently
}
}
}
第二部分,将 BuggyLabel 添加到应用程序并绑定 buggySetter:
Sectond, add BuggyLabel to an Application and bind buggySetter:
<fx:Script>
<![CDATA[
[Bindable]
public var foo:String = 'NULL has no properties';
]]>
</fx:Script>
<local:BuggyLabel buggySetter="{foo}"/>
为什么这个应用会无声无息地失败?
推荐答案
这个问题的答案实际上相当简短:这是 Flex SDK 工程师做出的架构决策.如果您查看 Flex 源代码,您会看到一个 try ... catch
块吞下了 Binding 中抛出的大多数错误.
The answer to that question is actually fairly short: it's an architectural decision made by the Flex SDK engineers. If you take a look at the Flex source code, you'll see a try ... catch
block swallowing most errors thrown in a Binding.
Pro:使绑定更容易使用,因为您不必考虑所有可能的错误状态
Pro: makes it easier to use bindings, since you don't have to account for all possible faulty states
缺点:调试可能会更困难(尽管如果您知道这可能发生并且您有良好的单元测试,您可以将那方面的挫败感减少到几乎为零)
Con: it can be harder to debug (though if you know this can happen and you have good unit tests, you can reduce frustration from that side to nearly zero)
我所说的源代码可以在mx.binding.Binding
(在'framework'项目中)的wrapFunctionCall()
方法中找到.这是相关部分:
The source code I was talking about can be found in mx.binding.Binding
(in the 'framework' project) in method wrapFunctionCall()
. Here's the relevant part:
try {
...
}
catch(error:Error)
{
// Certain errors are normal when executing a srcFunc or destFunc,
// so we swallow them:
// Error #1006: Call attempted on an object that is not a function.
// Error #1009: null has no properties.
// Error #1010: undefined has no properties.
// Error #1055: - has no properties.
// Error #1069: Property - not found on - and there is no default value
// We allow any other errors to be thrown.
if ((error.errorID != 1006) &&
(error.errorID != 1009) &&
(error.errorID != 1010) &&
(error.errorID != 1055) &&
(error.errorID != 1069))
{
throw error;
}
else
{
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + error);
}
}
}
这篇关于为什么 MXML 数据绑定会吞下 TypeErrors?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!