【发布时间】:2016-07-14 07:34:00
【问题描述】:
我的示例正在运行,但我对 ko.applyBindings() 语句的位置感到困惑。我使用 this approach 从单个 getJSON 请求中填充我的 ViewModel。但假设我需要 2 个 getJSON 请求。我移动了“var viewModel = new MyViewModel();”在 getJSON 之外,但 ko.applyBinding() 在两个 getJSON 方法中,我知道你不应该有 2 个绑定到同一个 VM。我尝试将 ko.applyBinding() 移到 getJSON 下方,但没有任何效果。因此,我将 ko.applyBinding() 留在了其中一个 getJSON 方法中,并调用了 VM 方法来设置来自另一个 JSON 调用的变量。它似乎有效,但我担心如果 JSON 请求在不同时间返回,是否存在可能导致问题的时间问题。
var MyViewModel = function() {
var self = this;
self.types = ko.observableArray();
self.states = ko.observableArray();
self.loadStates = function (states){
self.states = states;
}
}
var viewModel = new MyViewModel();
$(function () {
$.getJSON('json/typeArray.json', function(jTypes){
viewModel.types = jTypes;
ko.applyBindings(viewModel);
});
$.getJSON('json/stateArray.json', function(jStates){
viewModel.loadStates(jStates);
//ko.applyBindings(viewModel);
});
});
我可以使用嵌套的 JSON 请求,但我希望它们同时执行。
为什么 ko.applyBindings(viewModel) 不能移动到这个脚本的底部?我试过了,但我的数组都没有填充。
更新:是的,存在时间问题。有时第二个“状态”数组会在 UI 中更新,有时则不会。这显然取决于首先返回哪个 getJSON。所以我确实需要找到解决这个问题的方法。
这是在创建 viewModel 后尝试移动 applyBindings 的尝试,但没有成功(见评论):
var MyViewModel = function() {
var self = this;
self.name = "myViewModel";
self.states = ko.observableArray();
self.types = ko.observableArray();
self.loadStates = function (states){
self.states = states;
console.log("Set states in viewModel: " + self.states);
}
}
var viewModel = new MyViewModel();
ko.applyBindings(viewModel);
$(function () {
$.getJSON('json/typeArray.json', function(jTypes){
console.log("Setting types in viewModel: " + viewModel.name);
viewModel.types = jTypes;
//ko.applyBindings(viewModel);
});
$.getJSON('json/stateArray.json', function(jStates){
console.log("Setting states in viewModel: " + viewModel.name);
viewModel.loadStates(jStates);
//ko.applyBindings(viewModel);
});
});
【问题讨论】:
-
applyBindings 应该被调用一次,例如在视图模型创建后立即。您应该在 get json done 函数中更新 observable 属性:viewModel.types(jTypes) - 我想 jTypes 是一个数组。
-
我尝试在 viewModel 创建之后放置 applyBindings,但数组永远不会在 HTML 页面上得到更新。当我取消注释 getJSON 中的 applyBindings 时,它工作正常。请注意,console.log 条目表明 viewModel 在所有情况下都会正确更新。
-
除了@TSV 所说的之外,您还可以使用
Promise.all()来确保在调用回调之前加载所有json:参见示例jsfiddle.net/axLokczs/2 -
这是一个 ko 例子jsfiddle.net/axLokczs/3
-
如果您使用我的建议(
Promise.all()),您提到的种族问题就解决了
标签: knockout.js getjson