获取到组件的异步视图模型

Get async view model to component

本文关键字:视图 模型 异步 组件 获取      更新时间:2023-09-26

我想从服务器获取视图模型并在我的组件中使用它。可能吗?我的尝试,显然不起作用:

function getDummyViewModelAsync(){
   setTimeout(function(){
       cb({ foo: 1 });
   }, 500);
}
ko.components.register('my-component', {
   viewModel: {
       createViewModel: function(params, componentInfo) {
           getDummyViewModelAsync(function(viewModel){
               return viewModel;
           });
       }
   },
   template: ...
});

从我们在评论中的交流中不清楚您正在尝试做什么,而动态加载模块无法完成。您可以动态加载模块结构,当然也可以动态填充模块结构的元素。

如果你想手工完成所有事情,你可以这样做。将视图模型传递给获取函数。让 fetching 函数返回一个 promise,并在获取数据并将其放入视图模型中时解决它。您的模板甚至可以动态引用其他模板,因此您在加载时会看到一件事,而在完成后看到另一件事。

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>