What is the best way to invoke a function in one View Model from within another View Model?

I am looking to divide my DevExtreme Scheduler into two separate view models. One will be responsible for displaying the Scheduler itself, while the other will handle the Popup and button functionality. Despite having everything set up, I am struggling to call a function within the Popup view model.

$(document).ready(function () {

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

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

});

Within my Scheduler, I have a click handler where I need to call the loadData function from the popup view model.

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

I attempted calling it using popup.loadData(data); and viewPopup().loadData(data);, but neither worked. I received an error stating popup.loadData() is not a function. How can I successfully achieve this?

Answer ā„–1

In most cases, a primary viewmodel is created and sub-viewmodels are bound using the with binding:

var MainApp = function() {
  this.taskManager = new TaskViewModel();
  this.modalWindow = new ModalView();
}

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

This would be represented in the HTML as:

<body>
  <div data-bind="with: taskManager" id="TaskManagerSection"></div>
  <div data-bind="with: modalWindow" id="ModalWindowSection"></div>
</body>

Although it is not typically recommended, you can access the other viewmodel by using $root.taskManager from modalWindow, and $root.modalWindow from taskManager.

An alternative approach could involve passing a reference to the modalWindow viewmodel during instantiation.

A third possibility is implementing a "postbox" design pattern (such as this plugin developed by R. Niemeyer).

Answer ā„–2

Within my scheduling system, I have a click event listener that needs to call the loadData function located in the popup view model.

Therefore, the scheduler viewmodel must have access to the popup view model. To accomplish this, switch the order of declaration and pass a reference as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide to reordering table rows by drag-and-drop with JavaScript

Seeking assistance with swapping table rows using JQuery UI. Although successful in the swap, struggling to retrieve row numbers during the drag and drop event. Understanding the row number is essential for subsequent tasks. Any help would be greatly appre ...

Developing an ASP application using the MVP pattern to return JSON data can be transformed into a S

Iā€™m looking to incorporate the following code into a sails js Controller public JsonResult GetEvents() { //Using MyDatabaseEntities as our entity datacontext (refer to Step 4) using (MyDatabaseEntities dc = new MyDatabaseEntities()) { ...

What is the best way to implement the addMore event in my custom slot components when working with Vue Formulate?

I need help customizing the 'add more' button for group repeatable fields in Vue Formulate. I have created a custom slot component that is functioning correctly, but I am struggling to determine the click event needed to add another field when th ...

Observing the vertical dimension of a VueJS element

Can a VueJS watcher be used to monitor changes in the height of an element? I'm currently working on improving the filters section of a search results page. However, I'm facing difficulty in detecting when the results change so that the filters ...

Apologies, the system encountered an issue while trying to access the "name" property which was undefined. Fortunately, after refreshing the page, the error was successfully resolved

When the profile route is accessed, the code below is executed: import React, { useState, useEffect } from 'react' import { Row, Col, Form, Button } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' ...

What is the best way to adjust the fill animation of an inline svg based on the movement of the mouse within the parent div?

Can the fill of an inline SVG path be animated to change as the mouse moves across the page? ...

Is it feasible to convert a Google Drive spreadsheet into JSON format without needing the consent screen?

I'm working on incorporating a JSON feed directly from a private spreadsheet (accessible only via link) onto my website. In order to do this, I must create a new auth token using OAuth 2.0, which is not an issue. However, the Google Sheets API v4 mand ...

The prototype chaining for JavaScript inheritance was not functioning as expected

I have been studying Stoyan Stefanov's book on JavaScript Patterns and I seem to be stuck...I am having trouble inheriting the prototype. What could I possibly be doing wrong? (Please execute this code in NodeJS) // implementing inheritance function ...

Finding alternative solutions without using the find() method when working with Angular

How can I use an equivalent to find(".class") in AngularJS? I came across this solution: //find('.classname'), assumes you already have the starting elem to search from angular.element(elem.querySelector('.classname')) I attempted to ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

What is the simplest method for preserving the Redux state?

What is the most efficient method to maintain state in Redux even after a website refresh? I would prefer not to rely on redux-persist if there are alternative options available. ...

I encountered a "TypeError: Unable to access property 'name' of undefined" error when attempting to export a redux reducer

UPDATE: I encountered an issue where the namePlaceholder constant was returning undefined even though I was dispatching actions correctly. When attempting to export my selector function, I received an error: https://i.sstatic.net/MwfUP.png Here is the c ...

A stylish method for converting CSV data into XML format using Node.js and Express

I am in search of a sophisticated solution to convert CSV files into hierarchical XML format based on a specific template within a Node/Express server. For example, if the CSV is of Type Template "Location": Name,Lat,Lon,Timezone name,lat,lon,timezone it ...

Using the ternary operator in React to implement inline styles

Within my React/Typescript project, I aim to dynamically exhibit a color based on the presence or absence of a value in payload[1]. In the code snippet below, note the usage of an inline style tag. <li className="recharts-tooltip-item" style={ ...

Tips for enlarging the box width using animation

How can I create an animation that increases the width of the right side of a box from 20px to 80px by 60px when hovered over? What would be the jQuery code for achieving this effect? ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

Show or hide side menu depending on when a div reaches the top of the

I have a side menu that opens when a specific div reaches the top of the window. The menu includes a toggle button for opening and closing it. However, I am encountering an issue where the script keeps closing the menu on scroll even after manually openi ...

Activating list anchor upon click

I have a list that looks like this: <!-- List --> <ul class="nav nav-sm nav-tabs nav-vertical mb-4 steps-sampling"> <li class="nav-item"> <a class="nav-link active" id="link1" href="{{ ...

Experiencing difficulty when attempting to save a zip file to the C drive

I came across this code snippet on SO and decided to use it for my project. The goal is to send a simple 1.5mb zip file and save it on my C drive by making a request through Postman with the binary option enabled, sending the zip file to localhost:3012. c ...

Struggling to locate a route for the React styled components image

I'm having trouble locating the correct path for the image in my React styled components. I believe the path is correct, but could the issue be related to styled-components? Check it out here import styled from "styled-components"; export defaul ...