使用计算值访问 Knockout 中父视图模型中的函数
我正在尝试使用在子视图模型内部的主视图模型中定义的函数。我创建了一个小提琴,我认为它应该展示我正在尝试做的事情,但无法正常工作此处< /a>.还有更好的方法来完成我正在做的事情吗?
I am trying to use a function that is defined in my main view model from inside a sub view model. I have created a fiddle that I think should demonstrate what I am trying to do and doesn't work correctly here. Also is there a better way to accomplish what I am doing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您希望能够从子零件模型中查找父视图模型中的制造商列表。我改变了你的小提琴中的一些东西,并创建了一个新的东西来解决这个问题:
http://jsfiddle.net/johnpapa/dsZ76/
首先,
数据绑定
属性在应该使用文本时却使用了值。标记还应该使用结束 p 标记。另外,您绑定到制造商属性,但这是返回的对象,因此它应该是
manufacturer().name
。在 JavaScript 中,我将“this”添加为计算的第二个参数。然后“this”成为所有者,因此您可以在计算函数内使用它来表示零件模型。然后我更改了执行查找的函数以进行相等性检查,而不是使用 stringStartsWith 。
getManaufacturers
的定义已移至调用创建零件之前(因为零件模型会调用它)。最后,我将“self”传递给 Part 函数,它变成了父参数。这应该可以做到。
I think you wanted to be able to lookup the manufacturer list in the parent viewmodel from the child Part model. I changed a few things in your fiddle and created a new one that resolves this:
http://jsfiddle.net/johnpapa/dsZ76/
First, the
data-bind
attributes were using value when they should have been using text. The<p>
tags should also use a closing p tag. Also, you were binding to the manufacturer property, but that is the object being returned so it should have beenmanufacturer().name
.In the JavaScript, I added "this" as the second parameter to the computed. "this" then becomes the owner so you can use it inside the computed function to represent the Part model. Then I changed your function that does the lookup to do an equality check instead of using
stringStartsWith
. The definition for thegetManaufacturers
was moved before the call create the Parts (because the Parts models call it). Finally, I pass in "self" to the Part function, which turns into the parent parameter.This should do it.
约翰比我快:)我做了类似的改变。 http://jsfiddle.net/gurkavcu/qKFHB/
John is faster than me :) I made the similar changes. http://jsfiddle.net/gurkavcu/qKFHB/