【发布时间】:2019-02-20 19:14:20
【问题描述】:
我需要用 KnockoutJS 实现一个有趣的效果。假设我有一个最简单的模型:
var Item = function () {
var self = this;
self.title = ko.observable("");
};
当然我有一个 ViewModel:
var ItemList = function () {
var self = this;
self.list = ko.observableArray();
}
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);
});
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());
<div data-bind="foreach: list">
<span data-bind="text: title"></span>
</div>
【问题讨论】:
标签: javascript ajax knockout.js