我正在使用非常灵活的 KnockoutJS 库创建一个应用程序,但我遇到了一个障碍。在 html 页面上,我有一个普通的 <select>
我想加载从 Web 服务返回的 JSON 数据的控件。
我定义可观察数组如下:
var laborRow = function () {
this.positions = ko.observableArray([]);
};
当页面加载时,进行 ajax 调用并返回数据。在回调中,我执行以下操作:
success: function (msg) {
laborRow.positions = msg;
}
根据 KO 文档,我希望我会像这样设置结果:
laborRow.positions(msg);
但是,这只会抛出一个错误,指出“laborRow.positions in not a function”
html中的模板如下:
<tbody data-bind='template: {name: "laborRowTemplate", foreach: laborLine}'> </tbody>
</div>
<script type="text/html" id="laborRowTemplate">
<tr>
<td><select data-bind='options: positions, optionsText: "Title", optionsCaption: "select", value: selectedPosition '></select></td>
</tr>
</script>
laborRow
object 是绑定(bind)到页面的 ViewModel 的属性。无论出于何种原因,这都行不通。要添加另一个皱纹,如果我添加代码以查看 observableArray 并打印出一些数据,数据就在那里。所以它正在加载成功。
如有任何想法,我们将不胜感激。
我的示例案例的完整代码:
var laborRow = function () {
this.positions = ko.observableArray([]);
};
var projectEstimate = function () {
this.laborLine = ko.observableArray([new laborRow()]);
};
var projectViewModel = new projectEstimate();
ko.applyBindings(projectViewModel);
//and the code in the callback function on ajax success
success: function (msg) {
laborRow.positions = msg;
//laborRow.positions(msg); **this does not work - error is laborRow.positions is not a function**
},
和 html:
<tbody data-bind='template: {name: "laborRowTemplate", foreach:
laborLine}'> </tbody>
<script type="text/html" id="laborRowTemplate">
<tr>
<td><select data-bind='options: positions, optionsText:
"Title", optionsCaption: "select", value: selectedPosition '></
select></td>
</tr>
</script>
最后,感谢肖恩在下面的评论,我能够通过修改回调中的代码使其正常工作,如下所示:
success: function (msg) {
projectViewModel.laborLine()[(projectViewModel.laborLine().length-1)].positionList(msg);
}
最佳答案
问题是你还没有真正创建你的模型:
var laborRow = function () {
this.positions = ko.observableArray([]);
// will only be called if you call var some_var = new laborRow()
};
将您的函数更改为裸对象(如 Knockout docs 所示):
var laborRow = {
positions: ko.observableArray([])
};
并且您将能够调用 laborRow.positions(msg);
并让它工作。
编辑
根据新代码,laborRow
仍未实例化——如果您在代码中的其他地方设置 var laborRow
(可能是在 ajax 请求周围),那么您需要确保您的调用堆栈如下所示:
projectViewModel.laborLine()[0].positions()
// This will return the array you're looking for.
// The key is that laborLine is a `getter` not an attribute
我多次被“ko 变量是 getter
而不是 attributes
”的错误困扰...您的代码可能会发生这种情况吗?
关于javascript - ObservableArray 不反射(reflect)数据更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4432731/