我最终将在同一页面上使用多个 viewModel,因此我试图弄清楚如何将 viewModel 作为变量传递给函数,以便进行我的 ajax 调用。我正在尝试更新这个跨度:
<span data-bind="text: AnswerText"/></span> <span data-bind="text: GetFormattedDate() "/></span>
这段代码可以正常工作并正确填充来自 GetFormattedDate 的值:
var viewModel1;
$(document).ready(function () {
var jsonDataToSend = { questionConfigurationID: 1 };
$.ajax({
url: "SomePage.aspx/GetAnswerAndComments",
type: "post",
dataType: "text json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonDataToSend),
success: function (msg) {
var result = msg.d;
if (result != null) {
viewModel1 = ko.mapping.toJS(result);
ko.applyBindings(viewModel1, document.getElementById("divAnswerAndComment1"));
}
}
});
});
function GetFormattedDate()
{
var date = "";
if (viewModel1.InsertDate != null)
{
date = new Date(parseInt(viewModel1.InsertDate.substr(6)))
}
return date;
}
但是,当我将 $document.ready 函数替换为调用 GetFormattedDate 时将 viewModel 作为变量传递的另一个函数时, viewModel1 未定义(见下文)。我很确定它与 viewModel1 的范围有关,但我无法弄清楚到底是什么问题。
var viewModel1;
$(document).ready(function () {
GetAnswersAndComments(1, viewModel1);
});
function GetAnswersAndComments(questionID, currentViewModel) {
var jsonDataToSend = { questionConfigurationID: questionID };
$.ajax({
url: "ControlWebMethods.aspx/GetAnswerAndComments",
type: "post",
dataType: "text json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonDataToSend),
success: function (msg) {
var result = msg.d;
if (result != null) {
currentViewModel = ko.mapping.toJS(result);
ko.applyBindings(currentViewModel);
}
}
});
}
function GetFormattedDate()
{
var date = "";
if (viewModel1.InsertDate != null)
{
date = new Date(parseInt(viewModel1.InsertDate.substr(6)))
}
return date;
}