请帮助我理解为什么这个计算的可观察量无法访问可观察量。
这是小提琴 - http://jsfiddle.net/iRamesh/36N4m/
不确定为什么计算observable 没有返回任何值。我知道如何使其工作,但不确定为什么当前代码不起作用。请帮忙
this is the fiddle - http://jsfiddle.net/iRamesh/36N4m/
Not sure why computed observable is not returning any value. I know how to make it working but not sure why the current code is not working. please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
计算的可观察量在创建时立即评估。在您的情况下,
viewModel
尚未创建,因此这会导致错误。有几个替代方案: -
在初始对象文字之外创建它:
- 在函数中创建视图模型:
computed observables are evaluated immediately on creation. In your case,
viewModel
has not been created yet, so this causes an error.A couple alternatives:
-Create it outside of your initial object literal:
-Create your view model in a function:
对象字面量的创建非常简单,这使得它们非常棒。但这是我更喜欢使用函数创建视图模型的原因之一。使用对象文字,您可以扩展视图模型并创建计算...或者使用函数,您可以在一个函数语句中完成这一切,正如 @RPNiemeyer 指出的那样。
另一种选择是使用我最喜欢的揭示模块模式: http://jsfiddle.net/johnpapa/36N4m/1/
object literals are quite simple to create, which makes them awesome. But this is one of the reasons I prefer using functions to create view models. With an object literal you could just extend the view model and create the computed ... or with the function you can do it all in one function statement, as @RPNiemeyer points out.
Another option is to use the revealing module pattern, which I like best: http://jsfiddle.net/johnpapa/36N4m/1/
除了 @RPNiemeyer 的解决方案之外,还有另一种选择:
计算回调引用外部作用域中的 viewModel 变量,并且 deferEvaluation 确保计算的回调仅在需要时调用,因为在创建时 viewModel 变量还没有准备好。
In addition to the solution from @RPNiemeyer, there is yet another alternative:
The computed callback refers to the
viewModel
variable from the outer scope, anddeferEvaluation
makes sure the computed will only be called when needed, because at creation time theviewModel
variable won't be ready.