KnockoutJS:显示HTML - 填充HTML

问题描述 投票:0回答:2

我需要用KnockoutJS实现一个有趣的效果。想象一下,我有最简单的模型:

var Item = function () {
    var self = this;
    self.title = ko.observable("");
};

当然我有一个ViewModel:

var ItemList = function () {
var self = this;
self.list = ko.observableArray();
}
Then the fun begins. Right here in the ViewModel I get a few blocks of HTML markup. How many-is unknown. For each block I need to immediately show HTML-markup:

var blocks = await getBlocks();
$.each(blocks, function (index, value) {
    //At this point (as planned), the blocks should be displayed 
    //together with a rotating loading animation.
    self.list.push(new Item());
});

接下来(再次在ViewModel中)我需要获取数据来填充这些块:

$.each(self.list(), async function (index, value) {
    var data = await getData("some-url");
    //At this point, the blocks should be filled with data, 
    //and the spinning loading animation should disappear.
    self.list().push(data.results[0].title);
});
And now all together:

 var Item = function () {
    var self = this;
    self.title = ko.observable("");
};

var ItemList = function () {
    var self = this;
    self.list = ko.observableArray();
    var blocks = await getBlocks();
    $.each(blocks, function (index, value) {
        self.list.push(new Item());
    });

    $.each(self.list(), async function (index, value) {
        var data = await getData("some-url");
        self.list().push(data.results[0].title);
    });
};

ko.applyBindings(new ItemList());
HTML for all this ugliness looks very simple:

<div data-bind="foreach: list">
    <span data-bind="text: title"></span>
</div>
This approach does not work as expected. And I do not understand how you can do this with KnockoutJS. Is that even possible?
javascript ajax knockout.js
2个回答
1
投票

这是一个假设的例子:

  • 有一个电话告诉我们最终会呈现多少项目
  • 对于每个项目,都需要完成一个调用来呈现实际的UI

我已经使各个项目负责他们自己的数据加载。这使得可以更容易地将可以以任何顺序返回的接收数据写入相应的列表项。

您将看到UI呈现的步骤:

  1. 检索用于呈现初始列表的数据的调用正在加载:显示常规加载消息
  2. 我们为我们检索的每个项目创建了一个列表项。所有项目都已开始加载数据,但会显示加载状态,直到完成为止
  3. 逐个加载单个数据,列表元素接收其内容。

const { getProductIdsAsync, getProductAsync } = apiMethods();

function Item(id) {
  this.name = ko.observable(null);
  this.loading = ko.pureComputed(() => !this.name());
  
  getProductAsync(id).then(this.name);
};

Item.fromId = id => new Item(id);

function List() {
  this.items = ko.observableArray([]);
  this.loading = ko.pureComputed(() => !this.items().length);
  
  getProductIdsAsync()
    .then(ids => ids.map(Item.fromId))
    .then(this.items);
}

ko.applyBindings({ list: new List() });


// Mocking of some async API, not relevant to question:
function apiMethods() {
  const productCatalogDB = {
    1: "Apples",
    2: "Oranges",
    3: "Bananas"
  };

  const delayed = (f, minT, maxT) => 
    (...args) => 
      new Promise(res => {
        setTimeout(
          () => res(f(...args)),
          minT + Math.random() * (maxT - minT)
        )
      });

  return {
    getProductIdsAsync: delayed(
      () => Object.keys(productCatalogDB), 500, 1200),
    getProductAsync: delayed(
      id => productCatalogDB[id], 500, 1500)
  };
}
.loading {
  opacity: .6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<p data-bind="visible: list.loading">
  Loading catalog ids...
</p>

<ul data-bind="foreach: list.items">
  <li data-bind="css: { loading: loading }, text: name() || 'Loading...'">
    
  </li>
</ul>

2
投票

这行代码显然是错误的:

self.list().push(data.results[0].title);

它应该是:

value.title(data.results[0].title);
© www.soinside.com 2019 - 2024. All rights reserved.