以下是我的ViewModel里面我定义的var self = this;我的代码中有另一个foreach绑定工作,但那个不在ajax请求中。初始UI加载有效。我知道self.wikiData正在通过使用console.log(self.wikiData());进行测试而更新,但它没有在UI中更新。我在ajax请求之外有类似的工作。
self.wikiData = ko.observableArray([{title: ko.observable("testing"), url: ko.observable("code")}, {title: ko.observable("this"), url: ko.observable("works")}]);
$.ajax({
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + marker.title + "&callback=wikiCallBack",
dataType: 'jsonp',
success: function(response) {
// TODO figure out why ko array isnt updating
// Clear wikiData array's contents
self.wikiData = ko.observableArray([]);
// articleList is just an array is strings
var articleList = response[1];
if (articleList.length < 1) {
self.wikiData.push({
title: ko.observable("No articles found"),
url: ko.observable("#")
});
}
for (var i = 0; i < articleList.length; i++) {
articleStr = articleList[i];
self.wikiData.push({
title: ko.observable(articleStr),
url: ko.observable("http://en.wikipedia.org/wiki/" + articleStr)
});
}
// Push wiki attribution regardless of whether articles were found
self.wikiData.push({
title: ko.observable("Courtesy of Wikipedia API"),
url: ko.observable("https://www.mediawiki.org/wiki/API:Main_page")
});
//clearTimeout(wikiRequestTimeout);
if (self.isWikiMenuVisible() === false) {
self.clickHamburgerWiki();
}
}
});
<ul data-bind="foreach: wikiData">
<li class="wiki-list-item">
<a data-bind="text: title, attr:{href: url}"></a>
</li>
</ul>
答案 0 :(得分:0)
想出来。我最终删除了observable,因为我只需要跟踪observableArray中的对象,而不是操纵对象本身的内部数据。以下是其他所有内容:
$.ajax({
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + marker.title + "&callback=wikiCallBack",
dataType: 'jsonp',
success: function(response) {
// TODO figure out why ko array isnt updating
// articleList is just an array is strings
var articleList = response[1];
var tempArray = [];
if (articleList.length < 1) {
tempArray.push({
title: "No articles found",
url: "#"
});
} else {
for (var i = 0; i < articleList.length; i++) {
articleStr = articleList[i];
tempArray.push({
title: articleStr,
url: "http://en.wikipedia.org/wiki/" + articleStr
});
}
}
tempArray.push({
title: "Courtesy of Wikipedia API",
url: "https://www.mediawiki.org/wiki/API:Main_page"
});
// Clear wikiData array's contents by redefining with new content
self.wikiData.removeAll();
tempArray.forEach(function(item) {
self.wikiData.push(item);
});
// Push wiki attribution regardless of whether articles were found
//clearTimeout(wikiRequestTimeout);
if (self.isWikiMenuVisible() === false) {
self.clickHamburgerWiki();
}
}
});
&#13;
HTML保持不变。
事实证明,让KO识别更新的方法是使用removeAll()函数清空observableArray,然后将新对象推入其中,而不是将observableArray重新分配给空数组。这是有道理的,因为重新分配删除了先前设置的绑定,而removeAll()离开它们。