0

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?

jay
  • 434
  • 1
  • 5
  • 25
  • I supposed it would be possible to push a callback down when the childViewModel is instantiated self.child = ko.observable(new childViewModel(callback)); then in self.childValue.subscribe.... I could trigger that callback but what is the best practice for something like that? – jay Jul 15 '20 at 18:51

1 Answers1

0

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>
jay
  • 434
  • 1
  • 5
  • 25
  • ko.reactor has a pretty easy implementation, I've used it in a few projects that have really deep recursive models that have to broadcast data changes up to the top level. https://www.npmjs.com/package/ko-reactor. You can either watch the entire viewModel or just certain props of a given viewModel. – Budhead2004 Jul 16 '20 at 14:11