knockout.viewmodel icon indicating copy to clipboard operation
knockout.viewmodel copied to clipboard

access parent object of view model

Open nmehlei opened this issue 12 years ago • 4 comments

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.

nmehlei avatar Aug 15 '13 10:08 nmehlei

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.

coderenaissance avatar Aug 21 '13 03:08 coderenaissance

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.

spring1975 avatar Aug 22 '13 17:08 spring1975

@spring1975 i seriously second that!!

oexza avatar Jan 06 '14 21:01 oexza

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

nathanmfast avatar Jan 30 '14 03:01 nathanmfast