I have a parent-child view model object structure set up and need to update an observable on the parent from the child. I've basically come up with two patterns for doing so:
1] Pass a reference of the parent property to the child and update the property from within the child:
var ParentViewModel = function(){
var self = this;
this.selectedItem = ko.observable();
this.child = ko.observable(new ChildViewModel(self.selectedItem));
}
var ChildViewModel = function(parentSelectedItem){
var self = this;
this.id = ko.observable();
this.parentSelectedItem = parentSelectedItem;
this.select = function(){
self.parentSelectedItem(self);
}
}
2] Create the child's select method on the parent and reference the parent observable locally:
var ParentViewModel = function(){
var self = this;
this.selectedItem = ko.observable();
var child = new ChildViewModel();
child.select = function(){
self.selectedItem(child);
}
this.child = ko.observable(child);
}
var ChildViewModel = function(){
this.id = ko.observable();
}
Neither of these patterns send me head over heels. The first one pushes the entire property reference into children view models, the second defines a child's function outside of the scope of the child.
Does anyone have any other pattern suggestions as to how this operation could be achieved in javascript in a clean and testable manner? Or am I more or less stuck with just these two options?