How To Cache jQuery Template In Backbone View via Ajax?

守給你的承諾、 提交于 2019-12-13 08:12:44

问题


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

回答1:


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
  }



回答2:


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();
        });
}


来源:https://stackoverflow.com/questions/8186477/how-to-cache-jquery-template-in-backbone-view-via-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!