我是 knockout.js 框架的新手,我陷入了一个相当简单的问题,即将 JSON 数组与 html UL 列表绑定。html标记如下:
<div id="genres">
<ul data-bind="foreach: GenreCollection">
<li>
<a href="#"><span data-bind="text: $data"></span></a>
</li>
</ul>
</div>
我使用以下标记来捕获作为模板绑定数据传入的 JSON 数据:
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
JSON输出是:
{
"GenreCollection": [
"Action & Adventure",
"Action Comedies",
"Action Sci-Fi & Fantasy",
"Action Thrillers",
"Anime Action",
"Bollywood Action & Adventure",
"British Action & Adventure",
"Classic Action & Adventure",
"Crime Action & Adventure",
"Foreign Action & Adventure",
"Independent Action & Adventure",
"Military Action & Adventure",
"Spy Action & Adventure",
"TV Action & Adventure"
]
}
视图模型:
function viewModel(){
var self = this;
self.GenreCollection = ko.observableArray([]);
self.addData = function (data) {
for (var item in data) {
self.GenreCollection.push(data[item]);
}
}
}
GenreNamespace.bindData = function (data) {
var obj = new viewModel();
obj.addData(data);
ko.applyBindings(obj);
}
GenreNamespace.getData = function (searchText) {
$.ajax({
url: 'Genre/SearchGenre',
type: 'POST',
data: JSON.stringify(searchText),
dataType: 'json',
processData: false,
contentType: 'application/json; charset=utf-8',
success: function (data) {
GenreNamespace.bindData(data);
},
error: function (message) {
alert(message);
}
});
}
任何人都可以帮助我弄清楚上述html模板中的问题所在。我正在使用 VS 2012 和 Knockout 2.1 框架。
谢谢