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