问题描述
我可以用两种不同的方式编写一个敲除js数据绑定表达式:
I can write a knockoutjs data binding expression in two different ways:
1. <div data-bind="text: FirstName"></div>
2. <div data-bind="text: FistName()"></div>
在第二个示例中,请注意FirstName之后的两个括号.他们俩似乎都工作.有区别吗?
Note the two parens after FirstName in the second example. They both seem to work. Is there a difference?
推荐答案
有区别.
仅当FirstName
是ko.observable
时,它们都将同时起作用.如果它是一个普通值,则只有第一个变体将起作用.
They will only work both if FirstName
is a ko.observable
. If it is a plain value, only the first variant will work.
可观察对象不直接保留其值.它是提供对值的访问的功能.因此必须调用以获取值(即严格正确的是text: FistName()
).
An observable does not hold its value directly. It is a function that provides access to the value. Therefore it must be called to get the value (i.e., strictly correct is text: FistName()
).
但是淘汰赛是有帮助的,并且可以预见.因此,如果您自己未执行此操作,它将为您调用可观察对象.
But knockout is helpful and anticipates that. Therefore it will call the observable for you if you did not do it yourself.
对此负责的是辅助函数ko.utils.unwrapObservable()
,该函数带有一个参数,确定它是可观察值还是纯值,并在两种情况下均返回其值.
Responsible for this is the helper function ko.utils.unwrapObservable()
, which takes a parameter, determines whether it is an observable or a plain value and returns its value in both cases.
淘汰赛在您定义的每个绑定上都使用此功能,因此,您自己调用可观察对象(text: FistName()
)还是让淘汰赛在后台进行(text: FirstName
)都没关系.
Knockout uses this function on every binding you define, so it does not matter if you call the observable yourself (text: FistName()
) or let knockout do it behind the scenes (text: FirstName
).
古怪:
敲除解析绑定表达式<binding>: <expr>
,并确定<expr>
是简单标识符还是更复杂的标识符.
Knockout parses the binding expression <binding>: <expr>
and determines whether <expr>
is a simple identifier or something more complex.
只要<expr>
是一个简单的标识符(如FirstName
),由于情况是明确的,敲除将自动应用unwrapObservable()
.
Whenever <expr>
is a simple identifier—like FirstName
—knockout will apply unwrapObservable()
automatically, because the situation is unambiguous.
但是,每当<expr>
更复杂时(例如'Dear ' + FirstName
),knockout都会根据表达式构造自定义函数.现在事情变得模棱两可了,您需要自己调用可观察对象,例如:'Dear ' + FirstName()
.
But whenever <expr>
is more complex—like 'Dear ' + FirstName
—knockout constructs a custom function from the expression. Now things become ambiguous and you are required to call the observable yourself, like this: 'Dear ' + FirstName()
.
比较: http://jsfiddle.net/Tomalak/cU4qw/
这篇关于Knockoutjs绑定到Property vs Property()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!