获取组件的异步视图模型 [英] Get async view model to component

查看:79
本文介绍了获取组件的异步视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从服务器获取视图模型,并在我的组件中使用它.是否有可能?我的尝试显然行不通:

I would like to fetch a view model from the server and use it in my component. Is it possible? My attempt, which obviously doesn't work:

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

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

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

推荐答案

根据我们在评论中的交流,您不清楚要使用动态加载模块完成哪些操作.您可以动态地加载模块结构,当然也可以动态地填充它的元素.

It's not clear from our exchange in the comments what you are trying to do that cannot be done with the dynamic-loading modules. You can load your module structure dynamically, and of course you can populate elements of it dynamically.

如果您想手动执行所有操作,则可以执行此操作.将您的viewmodel传递给fetching函数.让获取函数返回一个promise,并在获取数据并将其放入视图模型后对其进行解析.您的模板甚至可以动态引用其他模板,因此在加载时会看到一件事,而在完成时会看到另一件事.

If you want to do everything by hand instead, you can do that. Pass your viewmodel to the fetching function. Have the fetching function return a promise, and resolve it when it has fetched the data and put it in the viewmodel. Your template can even dynamically reference other templates, so you see one thing while loading and another when done.

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>

这篇关于获取组件的异步视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆