我有调用 ajax GET 的 getGeneral
函数。当 ajax 收到数据 (json) 时,它根据给定的 json 创建 KO 模型并返回创建的 KO。
当创建 Knockout 模型并分配值时,应该调用 knockout applybindings
。这是我的代码:
定义 GeneralModel
和一些相关函数(在“GeneralModel.js
”中):
var GeneralModel = function() {
//for now it is empty as data ar binded automatically from json
// CountryName is one of the properties that is returned with json
}
function getGeneral(pid) {
$.ajax({
url: "/api/general",
contentType: "text/json",
dataType: "json",
type: "GET",
data: { id: pid},
success: function (item) {
var p = new GeneralModel();
p = ko.mapping.fromJS(item);
return p;
},
error: function (data) {
}
});
}
这是从另一个文件 (GeneralTabl.html) 调用的,它应该调用 get 函数和 applyBindings
来更新 UI:
var PortfolioGeneral = getGeneral("@Model.Id");
ko.applyBindings(PortfolioGeneral, document.getElementById("pv-portfolio-general-tab"));
但是,在这种情况下,我遇到了错误(未定义 CountryName)。这是因为 applyBindings
发生在 ajax 返回数据之前,所以我正在对具有未定义属性的空模型执行 applyBindings。
从 Json 到 Model 的映射发生在这里并赋值: p = ko.mapping.fromJS(item);
我也可以在 GeneralModel 中填写所有字段,但没有必要(我猜):
var GeneralModel = function() {
CountryName = ko.observable();
...
}
它仍然会报错“CountryName is not defined”。
解决方案是什么?
1) 我能否以某种方式将 getGeneral
移动到 GeneralModel
中,以便获取数据成为 GeneralModel 初始化的一部分?
或
2) 也许我应该以某种方式“等待 ajax 结果”,然后才 applyBindings
?
或
我相信还有其他选择,我只是不太熟悉 KO 和纯 JS。
注意:我完全理解这是因为 Ajax 是异步调用,所以问题是考虑到我有两个单独的文件并且我需要从外部调用 getGeneral 并且它应该返回一些变量,如何重构此代码。
最佳答案
尝试使用返回的 promise 接口(interface):
function getGeneral(pid) {
return $.ajax({
url: "/api/general",
contentType: "text/json",
dataType: "json",
type: "GET",
data: {
id: pid
}
});
}
getGeneral("@Model.Id").done(function (item) {
var p = new GeneralModel();
p = ko.mapping.fromJS(item);
ko.applyBindings(p, document.getElementById("pv-portfolio-general-tab"));
}).fail(function () {
//handle error here
});
关于javascript - 等待ajax结果绑定(bind) knockout 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20121539/