Trigger parent ViewModel event from child change

297 Views Asked by At

Is there a way to allow events to be triggered on the parent view model when an observable on the child view model changes? Here's a quick example of what I'm talking about:

HTML:

<input data-bind="value: child().childValue"/>
<span data-bind="text: child().childValue"/>

JavaScript:

<script>
var viewModel = function(){
   var self = this;
    self.child = ko.observable(new childViewModel());
  self.child.subscribe(function(evt){
    console.log("parent updated" + evt);  
  });
}

var childViewModel = function(){
    var self = this;
  self.childValue = ko.observable("");
    self.childValue.subscribe(function(evt){
    console.log("child updated - " + evt);  
  });
}

ko.applyBindings(viewModel);
</script>

In the example above, only the childValue subscription in the childViewModel is triggered. Can you force that event up to the parent?

1

There are 1 best solutions below

1
On

I found a pretty straightforward solution, you can create a computed that binds to the JSON from the serialized child. When the JSON changes, that subscription is triggered):

    <script>
    var viewModel = function(){
       var self = this;
        self.child = ko.observable(new childViewModel());
      
        ko.computed(function () { return ko.toJSON(self.child()) }).subscribe(function () {
        console.log("parent updated");
        });
    
    }
    
    var childViewModel = function(){
    var self = this;
    self.childValue = ko.observable("");
    self.childValue.subscribe(function(evt){
    console.log("child updated - " + evt);  
  });
}
    
    ko.applyBindings(viewModel);
    </script>