title: KnockoutJS passing viewModel to function
body: <p>I'm going to end up with multiple viewModels on the same page so I'm trying to figure out how to pass the viewModel as a variable to a function in order to do my ajax calls.  I'm trying to update this span:</p>
  
  <pre><code>&lt;span data-bind="text: AnswerText"/&gt;&lt;/span&gt; &lt;span data-bind="text: GetFormattedDate() "/&gt;&lt;/span&gt;
  </code></pre>
  
  <p>This chunk of code works and correctly populates with a value from GetFormattedDate:</p>
  
  <pre><code>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;
  } 
  </code></pre>
  
  <p>But when I replaced the $document.ready function with a call to another function passing the viewModel as a variable when GetFormattedDate is called viewModel1 is undefined (see below).  I'm pretty sure it has something to do with the scope of the viewModel1 but I can't figure out exactly what the issue is.</p>
  
  <pre><code>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;
  } 
  </code></pre>