Obtain asynchronous view model for component

Is it possible to retrieve a view model from the server and incorporate it into my component? I attempted to do so with the following code snippet, but it is not working as expected:

function fetchViewModelFromServerAsync(){
   setTimeout(function(){
       cb({ foo: 1 });
   }, 500);
}

ko.components.register('my-component', {
   viewModel: {
       createViewModel: function(params, componentInfo) {

           fetchViewModelFromServerAsync(function(viewModel){
               return viewModel;
           });
       }
   },
   template: ...
});

Answer №1

It seems that there may be some confusion in our conversation through the comments regarding what you are attempting to achieve that cannot be accomplished using dynamic-loading modules. With dynamic-loading modules, you have the ability to load your module structure dynamically and populate its elements dynamically as well.

If you prefer to handle everything manually, it is possible to do so. Simply pass your viewmodel to the fetching function. The fetching function can then return a promise, which should be resolved once the data has been fetched and placed into the viewmodel. Additionally, your template can reference other templates dynamically, allowing for a seamless transition between loading and displaying content.

function getDummyViewModelAsync(populateMe) {
  return new Promise(
    function(resolve, reject) {
      setTimeout(function() {
        populateMe.cb = ko.observable('A value');
        resolve('whatever');
      }, 500);
    }
  );
}

ko.components.register('my-component', {
  viewModel: {
    createViewModel: function(params, componentInfo) {
      var vm = {
          template: ko.observable('loading'),
          ready: ready
        },
        ready = getDummyViewModelAsync(vm);
      ready.then(function() {
        vm.template('ready');
      });
      return vm;
    }
  },
  template: document.getElementById('selector').innerHTML
});

console.clear();
ko.applyBindings();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<template id='loading'>
  Loading...
</template>
<template id='ready'>
  Ta da!
  <div data-bind="text: cb"></div>
</template>
<template id='selector'>
  <!-- ko template: template -->
  <!-- /ko -->
</template>

<my-component></my-component>

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

jQuery behaving erratically following deployment to the testing server

I am encountering an issue with jQuery in a user control that utilizes a Telerik RadGrid: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script> <script type="text/javascript"> ...

What causes old data to linger in component and how to effectively clear it out

Fetching data from NGXS state involves multiple steps. First, we define the state with a default list and loading indicator: @State<CollectionsStateModel>({ name: 'collections', defaults: { collectionList: [], (...), isListLoading: true, ...

Enhance the appearance of Ionic popups

Can someone help me with resizing a pop up? I've been struggling to get it right. This is the popup template in question: <ion-view> <ion-content scroll="false" class=""> test </ion-content> < ...

Exploring the boundaries of React's useContext functionality

In my applications, I specialize in creating custom hooks for accessing state stores. For example, I typically define the hook like this: const store = new Store(); const StoreContext = createContext(store); StoreContext.displayName = "StoreContext"; fun ...

The hover feature on my website is making the picture flicker

I am experiencing an issue with a map on my website that contains four colored squares. When I hover over one of the squares, the image of the map changes to show the route corresponding to that color. However, this causes the image to shift position and i ...

By using .innerHTML to create an element, the validation of HTML form fields can be circumvented

After inserting a form field with standard HTML validation constraints (pattern & required), using the .innerHTML property does not trigger validation. While I understand the difference between creating an element with .innerHTML and document.createElement ...

Obtain individual information from XML

After fetching data from the server using ajax, I am looking to retrieve only a specific part of the data which is the name. How can I modify my code to achieve this? const url = 'https://jsonplaceholder.typicode.com/users' const xhr = new XMLH ...

How can AngularJS achieve ng-repeat functionality with multiple variables similar to ng-init?

When using ng-init, you have the ability to utilize multiple variables: ng-init="var1=value1; var2=value2" I attempted something similar with ng-repeat but unfortunately it did not work as expected ng-repeat= "var1 in var1s; var2 in var2s" Is there a p ...

Navigating in AngularJS with various URL parameters

Within my application, I am in need of using routes that require multiple attributes from the URL to be passed into PHP. The current setup that is functioning correctly is as follows: .when('/jobs/:type', { templateUrl: function(attrs){ ...

Confusing postback phenomena in ASP.NET web forms

I have developed a small script that successfully maintains the focused element during an async postback. However, I encountered an issue when tabbing through controls generated inside an asp:Repeater, where a full postback is unexpectedly triggered. Below ...

Receiving notifications about a user's location when they interact with points of interest

My goal is to find nearby establishments based on points selected by the user on a map through clicks. I successfully implemented a click handler on the map using google.maps.event.addListener to retrieve the lat/lng of the clicked location. The issue ari ...

Unlimited Caching: A Guide to Storing HTTP Responses permanently

Is there a way to send an HTTP response that will be cached by any client indefinitely, so that the browser can retrieve it from the local file system without making any new HTTP requests when needed? Just imagine using this for versioned client code in a ...

Passing an array with pre-defined variables using jQuery's Ajax functionality

Currently, I have a function set up to gather the contents of a form and send it to a PHP page for processing. However, I am facing an issue where no data is reaching the PHP page when sending it via POST or GET methods. function add_new_customer(){ $ ...

Matching wildcard paths using Express

Seeking help with routing in Express. I am trying to have both /m/objectID and /m/someslug/ObjectID directed to the same function. My current setup is as follows: app.get("/m/:id", ...); app.get("/m/(.*)/:id", ...); The first route is working properly, b ...

The intricate dance between JAVA and HTML

Can Java be compatible with HTML and JS? Is it possible for them to cooperate without using JSP? In order to connect the WEKA function, we utilized Java code through a JAR file, but now we also require HTML and JS links for visualization. Is there an alte ...

``The issue concerning the preloading layer on the website``

My experience with the website www.wirecreation.net is sometimes marred by an issue during the initial load. It seems that there is a margin of a few pixels on the gray div containing the logo and progress bar at times, but other times it appears with zero ...

Error: CSRF token not found or invalid. What is the procedure for transmitting a CSRF token from the frontend to the backend?

In my Django project, I have a task that involves sending a date string from the frontend to the backend. On the frontend, I am utilizing JavaScript's fetch method. async function getCustomerInDeliveryDate(deliveryDate : String) { con ...

The toggle button for columns is not triggering the callback action

When working with the following JSFiddle, I noticed that the action function does not seem to fire whenever a button to select a column in the column visibility tool is selected. Check out the code snippet below for reference: $(document).ready(function( ...

Transclusion with multiple slots in AngularJS

Attempting to incorporate a component in AngularJS 1.5.8 with multi-slot transclusion. The test performs well when utilizing a directive, however, with a component, it appears that the slot cannot be located!. This is how the component is declared app. ...

In vue, pagination links are displayed as dots instead of numbers

Struggling to integrate pagination in vue. Facing an issue where the pagination links are appearing as dots, depicted in the attached image. The correct number of pagination links display and I can navigate through different pages using the side navigation ...