title: Value of this in a Durandal view model
body: <p>I have a problem that is baffling me at the moment.  I have a Durandal view model defined as below but the  value of <code>this</code> and other variables and functions as I step through the code chops and changes all over the place.</p>
  
  <p>I have commented the below as it's easier to show the various values as it moves through the code.
  </p>
  
  <pre><code>define(['durandal/plugins/router'], function (router) {
  
      var _outerRouter = router;
      var _outerSelf = this;
  
      var viewModel = function () {
  
          var _self = this;
          var _router = router;
          var _searchCriteria = ko.observable('');
          var _searchResults = ko.observableArray([]);
          var _messages = ko.observableArray([]);
  
          this.searchCriteria = _searchCriteria;
          this.searchResults = _searchResults;
          this.messages = _messages;
  
          this.search = function () {
  
              //
              // When called from the view bindings:
              //  &gt; this = viewModel
              //  &gt; _self = _outerSelf = _outerRouter = undefined
              //  &gt; _router = defined
              //
              var that = this;
  
              //
              // N.B. I set callback context to the viewModel
              //
              var req = $.ajax({
                  url: '../api/v1/things',
                  dataType: 'json',
                  context: this,  
                  data: {
                      searchCriteria: this.searchCriteria()
                  }
              })
              .done(function (results, status, request) {
  
                  //
                  // When called back:
                  //  &gt; this = viewModel 
                  //  &gt; _self = _outerSelf = _outerRouter = undefined
                  //  &gt; _router = defined
                  //
                  this.searchResults.removeAll();
                  this.messages.removeAll();
  
                  //
                  // Now when calling:
                  //  &gt; doShowResult = showResult = undefined
                  //  &gt; this.showResult = defined (have to use 'this')
                  //  &gt; displayMultipleResults = defined
                  //
                  if (results.length == 1) {                    
                      this.showResult(results[0]);
                  }
                  else {
                      displayMultipleResults(results);
                  }
              });
  
              function displayMultipleResults(results) {
  
                  //
                  // When called from ajax.done():
                  //  &gt; this = Window ?!?!
                  //  &gt; that = viewModel
                  //  &gt; _self = _outerSelf = _outerRouter = undefined
                  //  &gt; _router = defined
                  //
                  that.messages.push({ title: 'Found Lots of Things', body: "Please select...blah blah blah", type: 'info' });
  
                  for (var i = 0; i &lt; results.length; i++)
                      that.searchResults.push(results[i]);
              };
          };
  
          function doShowResult(result) {
  
              //
              // When called from ajax.done():
              //  &gt; this = viewModel
              //  &gt; _self = _outerSelf = _outerRouter = undefined
              //  &gt; _router = defined
              //
              // and then
              //
              // When called from the view bindings:
              //  &gt; this = the bound searchResult object
              //  &gt; _self = _outerSelf = _outerRouter = undefined
              //  &gt; _router = defined
              //
              _router.navigateTo('show-my-thing');
          }
  
          this.showResult = doShowResult;
      };
  
      return viewModel;
  });
  </code></pre>
  
  <p>And here is the view that it's bound to:
  </p>
  
  <pre><code>&lt;div&gt;
      &lt;div class="container-narrow"&gt;    
          &lt;div class="row-fluid"&gt;
              &lt;div class="span12"&gt;
                  &lt;h3&gt;Search&lt;/h3&gt;
  
                  &lt;p&gt;Enter search criteria...&lt;/p&gt;
  
                  &lt;div class="control-group"&gt;
                      &lt;input type="text" class="input-block-level" placeholder="Criteria" data-bind="value: searchCriteria"/&gt;
                  &lt;/div&gt;
  
                  &lt;div class="pull-right"&gt;
                      &lt;button class="btn btn-primary" data-bind="click: search"&gt;
                          &lt;i class="icon-search icon-white"&gt;&lt;/i&gt; Search
                      &lt;/button&gt;
                  &lt;/div&gt;
  
              &lt;/div&gt;
          &lt;/div&gt;
          &lt;br /&gt;
  
          &lt;!-- ko foreach: messages --&gt;
          &lt;div class="row-fluid"&gt;
              &lt;div class="alert" data-bind="css: { 'alert-error': type == 'error', 'alert-info': type == 'info', 'alert-success': type == 'success' }"&gt;
                  &lt;strong data-bind="text: title"&gt;&lt;/strong&gt; &lt;span data-bind="text: body"&gt;&lt;/span&gt;
              &lt;/div&gt;
          &lt;/div&gt;
          &lt;!-- /ko --&gt;
  
          &lt;!-- ko foreach: searchResults --&gt;
          &lt;div class="row-fluid"&gt;
              &lt;div class="span12 well well-small"&gt;                
                  &lt;div class="span10 search-result"&gt;
                      &lt;label&gt;Resut:&lt;/label&gt; &lt;span data-bind="{text: $data}"&gt;&lt;/span&gt;&lt;br /&gt;
                  &lt;/div&gt;
                  &lt;div class="span2"&gt;                    
                      &lt;button class="btn btn-mini btn-success pull-right" data-bind="click: $parent.showResult"&gt;
                          View
                      &lt;/button&gt;
                  &lt;/div&gt;
              &lt;/div&gt;        
          &lt;/div&gt;    
          &lt;!-- /ko --&gt;
  
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>My main question are:</p>
  
  <ol>
  <li><p>How come I can access <code>_router</code> but not <code>_self</code> (or any of the other variables (_searchCriteria etc.) everywhere?  </p></li>
  <li><p>How when the execution is inside <code>ajax.done()</code> and the value of <code>this</code> equals the viewModel but after it's stepped into displaySearchResult <code>this</code> equals the Window object?</p></li>
  <li><p>When inside <code>ajax.done()</code> <code>doShowResult</code> and <code>showResult</code> are <code>undefined</code> but <code>this.showResult</code> works fine, surely if <code>this</code> is <code>viewModel</code> then <code>showResult</code> is defined?</p></li>
  <li><p>Fortunately, in this case I only need to navigate in <code>doShowResult</code> and <code>_router</code> is defined when I call from both <code>ajax.done</code> and from the view binding. But what if I needed to access a value from the view model - this wouldn't be available if called from the view binding - how can I change the bindings or the code to support this (preferably in a non-hacky way)?</p></li>
  </ol>
  
  <p>Thanks in advance for any light anyone can shed on this.</p>