Category Archives: Jquery

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

Best practices for writing apps with Backbone.js

#1 Initial data for app:

Best option is using a server side template, we can simply embed the JSON data needed to populate our initial models right in the page itself.

var appInitialData = {{server_generated_json}};

#2 Rendering tons of models

While rendering with thousands of models and appending them inside container, will huge impcat on performance, may leads to freeze browser.

Continue reading Best practices for writing apps with Backbone.js