KnockoutJS将viewModel传递给函数

时间:2012-07-12 22:13:09

标签: knockout.js

我将在同一页面上结束多个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;
} 

1 个答案:

答案 0 :(得分:0)

您将viewModel1传递给GetAnswersAndComments。在函数内部,您对viewModel1的引用具有本地副本,并且此本地副本称为currentViewModel

然后使用currentViewModel = ko.mapping.toJS(result);设置该局部变量。 这不会触及viewModel1,因此它仍未定义。基本的Javascript