Utilize several external data sources to enhance data binding in knockout.js

Currently, I am developing a knockout.js wizard that requires fetching data from multiple remote sources using AJAX in order to properly display dropdown menus within the wizard.

There are 4 dropdowns in total and while the first two can be loaded initially, the last two depend on the selections made in the initial dropdowns.

So far, I have tried using jQuery promises and nesting data calls with their callbacks. However, I am open to suggestions on better ways to structure the view model code for the wizard.

Below is a snippet of the data loading code. Feel free to request more information if needed.

var postobj = {
    id: workoutId
};
var getWorkout = $.post("./RowingWorkouts/GetWorkoutUsingId", postobj);
var getDiet = $.post("./Diet/GetDietUsingId", postobj);
var getFeedback = $.post("./RowingWorkouts/GetWorkoutFeedback", postobj);

$.when(getWorkout, getDiet, getFeedback).done(function (workout, diet, feedback) {
    renderCharts(workout[0], diet[0], feedback[0])

    self.suggestedWorkouts = ko.observableArray();
    
    $.post("./RowingWorkouts/GetSuggested", { id: selectedOldWorkout }, function(result) { 
        self.suggestedWorkouts(result);
    });

});

This process involves multiple levels of complexity, which I would like to simplify if possible. Are there any overlooked design patterns or mistakes in my coding approach?

Answer №1

If you want to efficiently load data into your viewModel observables, you can implement lazy loading observable technique and utilize computed to subscribe when parent level observables are loaded.

function ViewModel() {
   this.workout = ko.onDemandObservable(ViewModel.prototype.getWorkout, this);
   this.diet = ko.onDemandObservable(ViewModel.prototype.getDiet, this);
   this.feedback= ko.onDemandObservable(ViewModel.prototype.getFeedback, this);
   this.suggestedWorkouts = ko.observable();

   ko.computed(ViewModel.prototype.listsLoaded, this);
}

ViewModel.prototype.listsLoaded= function () {    
   if (this.workout.loaded() && this.diet.loaded() && this.feedback.loaded()) {
        this.loadSuggestedWorkouts();
   }
}

ViewModel.prototype.getWorkout = function () {
   ...
}

ViewModel.prototype.getDiet = function () {
   ...
}

ViewModel.prototype.getFeedback = function () {
   ...
}

ViewModel.prototype.loadSuggestedWorkouts = function () {
  ...
}

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

Capture information and store it in a database through the use of AJAX technology

I want to implement AJAX for real-time saving of user input comments directly to the database. Here is where users can input their comments: <div class="comment"> <form action="comment.php"> <textarea cols="35" name="comment ...

JQuery, Draggable delete

I created a shopping cart with drag-and-drop functionality for nodes. http://jsfiddle.net/dkonline/Tw46Y/ Currently, once an item is dropped into the bucket (slot), it cannot be removed. I'm looking to add that feature where items can be removed from ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

Passport sessions do not retain persistence

Having some trouble implementing OAuth 2.0 login where the sessions don't persist after authentication is a common issue. Additionally, there seems to be a problem with the app getting stuck in the routes/bnetauth.js file during the redirect in the ca ...

Retrieving the current date with a static time string can be achieved using Moment.js

If it is currently May 19, 2021, how can I obtain the string 2021-05-19T23:59:00.000Z? I attempted using moment().format() but it just provides the current datetime string. I specifically require the time in the formatString to display as 23:59, resultin ...

What is the process for incorporating JavaScript-generated coordination into an HTML form?

As a newcomer to Javascript, I am on a mission to integrate geo coordination directly into an HTML form input field. After learning from W3Schools how to generate user latitude and longitude Coordination, I am now eager to input them directly into an HTML ...

What is the best way to select a name from the auto-suggested text box?

My database contains a list of names that I want to display when clicked on an item in the auto-complete text box. However, I'm currently having issues displaying the records. Can someone please assist me with this problem? Here is my code... <!DO ...

Undefined is the value assigned to Javascript Dot Notation

When using dot notation to access objects with a '.', I am encountering an issue that I cannot seem to figure out. The success function in my jQuery $.ajax function looks like this: success: function(data){ console.log('data = ' + da ...

Exploring the Contrast between Cursor and Stream in Node.js

When it comes to extracting large data from a database, there are options like using stream or cursor. I'm curious to find out which option is more efficient and also dive into how cursor and stream work internally in node js. ...

The toThrow() function in Jest seems to be malfunctioning

Even though my JS code throws the correct error, it still fails. Here is the relevant Jest code block: describe('operate', () => { test("works with addition", () => { expect(evaluate_expression("3+5")).toEqu ...

Setting a value in a hidden field using a dropdown menu

I am encountering an issue while working with a form and making an ajax request. Everything seems to be going smoothly except for assigning the value of a dropdown to a hidden variable. The scenario is this: You choose a previously completed assignment, w ...

Trouble with fill() function

Check out this JavaScript code snippet I wrote: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill( ...

Transfer the data in the columns of Sheet1 to Sheet2 and eliminate any duplicates using Google App Script

Is there a way to transfer only unique rows from a SOURCE Spreadsheet to a DESTINATION spreadsheet? Spreadsheet #1 (SOURCE) - This sheet contains ID's and Names, but has duplicate rows. There are over 500k rows in this sheet and it is view-only. Spre ...

Utilize Ajax and Nodejs to inject dynamic content into your webpage

Seeking assistance in implementing a project where a navigation bar on the page contains various items, and I aim to display the content of each tab without reloading the entire page. Utilizing Nodejs with the ejs template engine, my research hasn't l ...

The process of sending an array of objects to a Controller Action through a jQuery ajax request in .NET Core 2.2 fails to function as intended

When I stringify an array of objects, the controller action does not receive it and the parameter of the action (the model) is null. I have explored various solutions to this issue on StackOverflow, but none of them have resolved my problem. Here are the ...

Choosing Tags with Ajax in Select2

The JSON data below is fetched from /tags: [ { "id": "CSS", "text": "CSS" }, { "id": "HTML", "text": "HTML" }, { "id": "JavaScript", "text": "JavaScript" }, { "id": "jQuer ...

Value preselected in the dropdown menu

I need to display the 'Choose option' as a disabled option in a drop down list that is generated from another page. page1.php <div class="col-md-4"> <select class="form-control" name="task" id="task" required> ...

How can I get the class name of the drop destination with react-dnd?

Imagine having this component that serves as a drop target module. import { useDrop } from 'react-dnd'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function Draggable ...

Summing up numbers within a hierarchical table using jQuery

There are two tables, each with their own unique ID as shown below: <table id="cvo"> <tr id="1"> <td>C</td> </tr> <tr id="2"> <td>C</td> </tr> <tr id="3"> <td>O</ ...

Sending data to a React Dialog component using the OnClick event

I am a beginner learning React.js and currently experimenting with passing parameters to a dialog box using onclick events. <IconButton className={classes.approvebutton} onClick={() => handleDialogClick("approve",1)}> <ThumbU ...