Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

access parent object of view model #42

Open
nmehlei opened this issue Aug 15, 2013 · 4 comments
Open

access parent object of view model #42

nmehlei opened this issue Aug 15, 2013 · 4 comments

Comments

@nmehlei
Copy link

nmehlei commented Aug 15, 2013

Hey,
I'm currently migrating from the knockout mapping plugin to this plugin. One thing I did with the mapping plugin was to build constructor functions (pseudo-classes) for my more complex view models. This allowed me, through custom instantiation, to give those a reference to their parent view model. For example, order view model could get reference to Customer view model etc. Obviously one should try to minimize those connections, but sometimes they aren't avoidable.
While rebuilding those view models with the viewmodel-plugin, how does one do that here? With the extend mapping option, I don't see a way to get to a reference, since there is only the single argument.

@coderenaissance
Copy link
Owner

The problem is that the mapping happens leaves to root so the parent isn't necessarily in a state that's ready to be referenced. One way to handle this is to extend the parent and make modifications to it's children in the parent's extend. Another is to reference the parent via the viewmodel such as:

var model = ...
var viewmodel = ko.viewmodel.fromModel(model, {
extend:{map:{"root.item.property":function(prop){
 item.extendedProp = ko.computed({
   read:function(){
     //closure over viewmodel, deferEvaluation makes this safe
     var data = viewmodel.item.anotherProp();
   },
   deferEvaluation:true
 });
}}}});

These two techniques have worked well for me so far.

@spring1975
Copy link

I've been interested in doing this as well. Do you have an example of the other technique you're talking about just for reference? Love to see a fiddle if you've got time.

@oexza
Copy link

oexza commented Jan 6, 2014

@spring1975 i seriously second that!!

@nathanmfast
Copy link

You rock @coderenaissance. Just stumbled across this and your method of using deferEvaluation was exactly what I was looking for. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants