我正在尝试执行简单的ko
绑定,但如果执行以下操作会出错:
<div data-bind="foreach: collections">
.....
</div>
这是js代码:
define(
['jquery', 'knockout', 'RestClient', 'Constants'],
function($, ko, ccRestClient, Constants) {
var collections = ko.observableArray([]);
return {
onLoad: function() {
RestClient.request(Constants.ENDPOINT, input,
function(data) {
for (var i = 0; i < data.childData.length; i++) {
var level = {
"firstName": ko.observable(data.childData[i].firstName),
"Id": ko.observable(data.childData[i].Id)
};
categories.push(level);
}
});
}
}
}
);
我收到以下错误:
错误 - 未定义集合
答案 0 :(得分:3)
使用Knockout,你应该使用像ViewModel这样的东西,它只是一个具有你将在视图中使用的属性和函数的对象。我在你的代码中看不到。它应该看起来像:
function ViewModel() {
var self = this;
self.collections = ko.observableArray();
// do what you want with collections
}
在视图onload函数中,您应该使用ko.applyBindings(new ViewModel())
将所有绑定应用于视图。只有这样,您才能使用data-bind
属性访问它们。
<强>更新强>
如果在内部应用ko.applyBindings,则问题在于您声明集合的方式。您使用var
将其设为私有变量,但应将其设为应用ko.applyBindings
的模型的属性。如果代码中的函数返回的对象是模型,只需按照以下方式进行:
return {
collections: ko.observableArray(),
onLoad: //...
}
如果没有,那么在没有关于您的申请的更多细节的情况下,我无法告诉您解决方案。
答案 1 :(得分:0)
首先,你的js代码中有一个错误的类型。请参阅定义
function($, ko, ccRestClient, Constants) {
然后你使用RestClient,而不是上面的ccRestClient
RestClient.request(Constants.ENDPOINT, input,
用ccRestClient替换RestClient。
答案 2 :(得分:0)
听起来很奇怪,删除use: strict
对我来说就是一招。