1
我将结束在同一页面上的多个viewModels,所以我想弄清楚如何将viewModel作为变量传递给一个函数以执行我的ajax调用。我试图更新此跨度:KnockoutJS将viewModel传递给函数
<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的viewModel1未定义时(见下文),将另一个函数传递给viewModel作为变量。我很确定它与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;
}
你真的不应该'applyBindings'这样的功能。应用一次,然后将更改推送到您的视图模型。绑定将使视图保持最新状态。 – Tyrsius 2012-07-12 22:50:41
我不确定我明白你的意思。 – mistyayn 2012-07-12 23:02:33
对'ko.applyBindings()'的调用应该只在*一次*之后。一旦绑定被应用,任何具有数据绑定的HTML将在视图模型更新时得到更新。如果这仍然没有意义,请考虑通过Knockout教程。 – Tyrsius 2012-07-12 23:04:13