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

The LoopBack framework encountered an issue where it could not execute the 'post' method due to being undefined

As a newcomer to loopback and node.js, I have successfully created two models - Rating and RatingsAggregate. Utilizing the loopback explorer, querying and posting against the API has been smooth. In an attempt to establish basic business logic, I am curre ...

Is it possible to stop an AjaxBehaviorEvent listener or send extra information to the f:ajax onevent function?

In the controller, I have created a listener that looks something like this: public class FooController { public void doSomething(AjaxBehaviorEvent evt) { closeDialogFlag = true; .. if(!isValid){ closeDialogFlag = f ...

Run audio player in the background with Google Chrome Extension

I am working on an extension and I want to have a page with an audio player that continues to play even when I click outside of the extension. I tried using the "background" attribute in the manifest file, but it seems to only work with javascript files. ...

Leverage the specific child's package modules during the execution of the bundle

Project Set Up I have divided my project into 3 npm packages: root, client, and server. Each package contains the specific dependencies it requires; for example, root has build tools, client has react, and server has express. While I understand that this ...

Incorporate VLC player into a webpage without any visible control options

Is there a way to embed a flash video in a webpage without showing any controls? I managed to embed a flash video using VLC with the following code: <embed src="img/Wildlife.wmv" height="480" width="640"> However, I want the video to play without ...

Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template: <body ng-controller="myCtrl"> {{loadDataSubject('${subjectList}')}} {{loadDataTopic('${topicList}')}} <h1 class = "bg-success" style="color: red;text-align: ...

When a new entry is added to the database, automatically refresh a <div> section within an HTML document

I have a basic webpage that showcases various products stored in the database. My goal is to implement an updater feature where, if a user adds a new product, the page will automatically display the latest addition in a specific div. I attempted to refere ...

Call a PHP function within a functions file using a JavaScript function

Seeking a way to navigate between PHP and JavaScript worlds with confidence. There's a collection of PHP functions stored neatly in custom_functions.php waiting to be called from JavaScript. As I delve into the realm of JavaScript and jQuery, my fam ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

Change the value in Vue through a single action (swapping out buttons)

I created a custom component that allows users to add points only once by clicking a button. I want to add an undo option to decrease the point value by 1 after it has been added. When a point is added, I'd like the button to change color to red and d ...

Is it possible to update parent data using a child component?

What is the correct way to update parent data using a child component? In the child component, I am directly modifying parent data through props. I'm unsure if this is the right approach. According to the Vue documentation: When the parent proper ...

Why is my JavaScript code functioning properly on jsfiddle but failing to work when run locally?

After recently creating JavaScript code that allows for form submission using the <form> tag, I encountered an issue when trying to implement it within an HTML page. Here is a snippet of the code: <script type="text/javascript"> var m ...

Revise directive following the dynamic addition of elements

My Objective: I aim to utilize directives for creating custom elements and dynamically inserting them into the view at various points in time. The Challenge: Upon dynamically adding custom elements to the view, they appear as raw HTML without the directi ...

Encountering an error with the node module timestampnotes: 'command not recognized'

I am encountering an issue while trying to utilize a npm package called timestamp notes. After executing the following commands: $npm install timestampnotes $timestamp I receive the error message: timestamp:126: command not found: slk Subsequently, I ...

Unable to execute AJAX POST request

https://i.stack.imgur.com/JqG7c.pngI have a JSON dataset like the one below: [ { "Password": "tedd", "Username": "john", "status": true } ] I need to consume this data using a POST method <label for="Username">Username:</label& ...

Deliver data in batches of ten when the endpoint is accessed

I am currently in the process of developing a web application using Next.JS and Node. As part of this project, I have created my own API with Node that is being requested by Next.JS. One particular endpoint within my API sends data to the front end as an ...

How to update the selected autocomplete item in Vue using programming techniques?

Although I am still learning Vue, consider the following scenario: <v-autocomplete v-model="defaultUser" :hint="`User: ${defaultUser.username}`" :items="users" :item-text="item =>`${item.firstName} - $ ...

Tips for testing parallel, mocked data requests in JEST by simulating cached responses with a 500ms limit

In order to simulate parallel requests fetching data from different sources, I have implemented tests that introduce artificial latency for each request. The goal is to return a simple string with an identifying digit to determine whether the data has been ...

What is the best way to transform a one-dimensional object array into a two-dimensional array in a Vue component, based on a specific key?

My vue modules are structured like this: [types.GET_PRODUCT_CATEGORIES] (state,{ stores }) { state.product_categories = {} console.log(stores); stores.forEach(message => { set(state.product_categories, message.id ...

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...