title: How To Cache jQuery Template In Backbone View via Ajax?
body: <p>I am using backbone.js and jQuery templates. What I'd like to do is set the view's template to a dom element. It looks something like this:</p>
  
  <pre><code>&lt;script id="templateElement" type="text/x-jQuery-tmpl"&gt;
      &lt;div class='foo'&gt;bar&lt;/div&gt;
  &lt;/script&gt;
  </code></pre>
  
  <p>When the view is initialized, it will see if the template exists with $.isFunction. If it doesn't it will get it from an external file and append the returned dom element to the body element and then set this.template to that dom element.</p>
  
  <p>The next time the view is called, that dom element should exist so there should be no reason to issue the AJAX call again. However, I'm finding that although this template is no longer null after the AJAX call, it is undefined even though setting it is part of the callback. as a result my AJAX call is issued every time the view is rendered even though #templateElement is part of the page. </p>
  
  <p>What's going on?</p>
  
  <pre><code>BbView = Backbone.View.extend({
      template: $('#templateElement').template(),
  
      initialize:
  
      //this.template is null at this point
  
           if(!($.isFunction(this.template))){
              $.get('template/file.html', function(templates){
                  $('body').append(templates);
                  this.template = $('#templateElement').template();
              });
      }
  
      //this.template is undefined at this point
      ...
  </code></pre>