Rick
Rick

Reputation: 119

KnockoutJs call function in other viewmodel of applyBindings

On a page I'm calling ko.applyBindings twice to iniate 2 view models. When viewModelOne saves successfully, I want to reload the other view model as some data is added in the backend as they are loosely linked.

Now I'm trying to call viewModelTwo.reloadData in saveSuccess() but I keep getting the error that it can't find the function whatever I try. (Uncaught TypeError: viewModelTwo.reloadData is not a function)

What is the correct way of calling a function from the other viewmodel in KnockoutJs? Could anyone point me in the right direction?

var viewModelOne = (function () {
     function reloadData(url) {
                ...
      }
      
      function saveSuccess(){
          viewModelTwo.reloadData('');
      }
});

var viewModelTwo = (function () {
     function reloadData(url) {
                ...
      }
});

ko.applyBindings(viewModelOne, document.getElementById("modelOneContainer"));
ko.applyBindings(viewModelTwo, document.getElementById("modelTwoContainer"));

Upvotes: 0

Views: 18

Answers (1)

Brother Woodrow
Brother Woodrow

Reputation: 6382

You could use a constructor function:

function ViewModelOne() {
  var vm = this;
  
  vm.reloadData = function() {
    console.log('vm1 reloaddata');
  }
}

var vm1 = new ViewModelOne();

function ViewModelTwo() {
  var vm = this;
  
  vm.reloadData = function() {
    vm1.reloadData();
    console.log('vm2 reloaddata');
  }
}
var vm2 = new ViewModelTwo();

ko.applyBindings(vm1, document.getElementById("modelOneContainer"));
ko.applyBindings(vm2, document.getElementById("modelTwoContainer"));

vm2.reloadData();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<div id="modelOneContainer"></div>
<div id="modelTwoContainer"></div>

Upvotes: 0

Related Questions