带有 WebApi 的 KnockoutJS。当我尝试使用自定义绑定时,我无法将绑定数据传递给自定义绑定函数。
我现在已经敲了两天的头,肯定在这里遗漏了一些东西。
任何指南、文章或示例代码将不胜感激。非常感谢。
<script>
function ViewModel() {
var self = this;
self.items = ko.observableArray();
// This is getting data, and tested have data returned.
var baseUri = 'api/items';
$.getJSON(baseUri, self.items);
}
$(document).ready(function () {
ko.bindingHandlers.testBinding = {
init: function (element, valueAccessor) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
// This is always 0.
alert(valueUnwrapped.length);
},
update: function (element, valueAccessor) {
var value = valueAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
// This is always 0.
alert(valueUnwrapped.length);
}
};
// Binding to Web Api data.
ko.applyBindings(new ViewModel());
// Test it with static data, and custom binding works. The length displayed 2.
//var viewModel = {
// items: ko.observableArray([{name: "Bob1"}, {name: "Bob2"}])
//};
//ko.applyBindings(viewModel);
});
</script>
<div data-bind="testBinding: items"></div>