How To Cache jQuery Template In Backbone View via

2019-08-24 01:21发布

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:

<script id="templateElement" type="text/x-jQuery-tmpl">
    <div class='foo'>bar</div>
</script>

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.

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.

What's going on?

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
    ...

2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-24 01:59

My best guess is that your this.template inside of the $.get is out of scope.

You might want to do

initialize:
var self = this;
//this.template is null at this point

     if(!($.isFunction(self.template))){
        $.get('template/file.html', function(templates){
            $('body').append(templates);
            self.template = $('#templateElement').template();
        });
}
查看更多
甜甜的少女心
3楼-- · 2019-08-24 02:14

Right. You've lost 'this' which is not your view in the call to $.get(). You can use underscore.bind to call the success callback in the context of your view.

However, you don't actually need to put the template into the DOM.

You can set the compiled template on the View prototype and it will be there for the next instance of this view. For example, something like...

BbView = Backbone.View.extend({

  initialize: function() {
    if(!($.isFunction(this.template))) {
      $.get('template/file.html', _.bind(function(templates) {
        BbView.prototype.template = $(templates).template();
      }), this);
    }
    // Now you have this.template, for this and all subsequent instances
  }
查看更多
登录 后发表回答