Backbone js load Async Template files

Template Manager plugin for Loading HBS template files:

file: templateManager.js

/*
  templateManager - Async Handlebars template loader/cacher.
  @author Mohan Dere
  @version 1.0
  @requires jQuery || zepto, underscore, Handlebars.js
*/


(function() {

  window.TemplateManager = (function() {
    var cache, defaults, fetchAndCache;

    defaults = {
      path: '/tpl/',
      ext: '.hbs'
    };

    cache = {};

    function TemplateManager(options) {
      this.options = options != null ? options : {};
      _.defaults(this.options, defaults);
      if (this.options.cache) {
        cache = this.options.cache;
      }
    }

    TemplateManager.prototype.load = function(tpl, callback) {
      if (_.has(cache, tpl)) {
        return callback(cache[tpl]);
      }
      tpl = fetchAndCache.apply(this, arguments);
      if (!callback) {
        return tpl;
      }
      return tpl.done(function(tplString) {
        if (callback) {
          return callback(tplString);
        }
      });
    };

    fetchAndCache = function(tpl) {
      var deferred, tplPath,
        _this = this;
      deferred = new jQuery.Deferred();
      tplPath = "" + this.options.path + tpl + this.options.ext;
      jQuery.ajax({
        url: tplPath,
        type: 'GET',
        dataType: 'text',
        success: function(tplString) {
          cache[tpl] = Handlebars.compile(tplString)
          cache[tpl].tplString = tplString;
          return deferred.resolve(cache[tpl]);
        }
      });
      return deferred;
    };

    return TemplateManager;

  })();

}).call(this);

Usage:

// Create the WordPress Backbone namespace.
var jwfpApp = {
    _views: {},
    _models: {},
    _collections: {},
    _vent: _.clone(Backbone.Events),
    tpl: new TemplateManager({
    path: jwfpAppData.tpl_path
  })
};

// Inside view file and in render function

var self = this;
jwfpApp.tpl.load('tpl/homePage', function(template) {
  self.$stageConatiner.html(template({});
});

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s