Expressingx
Expressingx

Reputation: 1572

How to call a function in a View Model inside another View Model?

I want to separate my DevExtreme Scheduler in 2 view models. One is for the actual Scheduler and the other one is to show the Popup and handle the buttons. However i have everything but i cannot call the function inside the Popup view model.

$(document).ready(function () {

    var model = new viewModel();
    ko.applyBindings(model, document.getElementById("BookingScheduler"));

    var popup = new viewPopup();
    ko.applyBindings(popup, document.getElementById("BookingPopup"));

});

Inside my scheduler i have a click handler and inside it i want to call the loadData function which is in the popup view model.

function viewPopup() {
   function loadData(data) {
   }
}

This is how i tried to call it popup.loadData(data); and viewPopup().loadData(data); and none of them work. I get popup.loadData() is not a function. How can i achieve that?

Upvotes: 0

Views: 264

Answers (2)

user3297291
user3297291

Reputation: 23372

Usually, you create one main viewmodel and bind sub-viewmodels using the with binding:

var App = function() {
  this.scheduler = new viewModel();
  this.popup = new viewPopup();
}

$(document).ready(function () {
  ko.applyBindings(new App());
});

With the HTML:

<body>
  <div data-bind="with: scheduler" id="BookingScheduler"></div>
  <div data-bind="with: popup" id="BookingPopup"></div>
</body>

Now, al though I'm not sure I'd recommend it, you can access the other vm using $root.scheduler from popup, and $root.popup from scheduler.

A better option could be to pass a reference to the popup viewmodel upon instantiation.

A third option is to use a "postbox" pattern (like this plugin by R. Niemeyer).

Upvotes: 1

Jamiec
Jamiec

Reputation: 136074

Inside my scheduler i have a click handler and inside it i want to call the loadData function which is in the popup view model.

Then the scheduler viewmodel needs a reference to the popup view model. Swap round the order you declare them, and pass a reference in

var popup = new viewPopup();
ko.applyBindings(popup, document.getElementById("BookingPopup"));
var model = new viewModel(popup);
ko.applyBindings(model, document.getElementById("BookingScheduler"));

Upvotes: 0

Related Questions