PlTaylor
PlTaylor

Reputation: 7525

Using a Computed Value that accesses a function in the parent viewmodel in Knockout

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?

Upvotes: 3

Views: 2332

Answers (2)

John Papa
John Papa

Reputation: 22298

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 been manufacturer().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 the getManaufacturers 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.

Upvotes: 5

Luffy
Luffy

Reputation: 2337

John is faster than me :) I made the similar changes. http://jsfiddle.net/gurkavcu/qKFHB/

Upvotes: 1

Related Questions