backbone.js - requirejs text plugin downloads all templates which are not required -
i'm using requirejs along text plugin load handlebar templates dynamically in backbone layout manager. on page load templates downloaded instead of specified one. in case shown below when want render footer files (header
, modal
) gets fetched instead of footer.tpl
.
templateloader.js
define(function (require) { var handlebars = require('handlebars'); var gettemplatefile = function (templatename) { var tmpl = null; switch (templatename) { case 'header': tmpl = require('text!../html/templates/header.tpl'); break; case 'footer': tmpl = require('text!../html/templates/footer.tpl'); break; case 'modal': tmpl = require('text!../html/templates/modal.tpl'); break; } return tmpl; }; var _compiled = function (tpl, context) { var compiled = handlebars.compile(tpl); return context ? compiled(context) : compiled; }; return { gettemplate: function (templatename, model) { return _compiled(gettemplatefile(templatename), model); } } });
myview.js - layoutmanager
app.views.storefooter = backbone.layout.extend({ beforerender: function () { this.$el.html(templates.gettemplate('footer')); } });
when check resources downloaded in chrome see modal.tpl
, header.tpl
should not there according above code.
this side-effect of syntax sugar, described in documentation :
define(function (require) { var dependency1 = require('dependency1'), dependency2 = require('dependency2'); return function () {}; });
the amd loader parse out require('') calls using function.prototype.tostring(), internally convert above define call this:
define(['require', 'dependency1', 'dependency2'], function (require) { var dependency1 = require('dependency1'), dependency2 = require('dependency2'); return function () {}; });
since parses function body string, has no way of seeing require
statements inside switch
guaranteed match 1 case
.
edit:
i thought fixed refactoring code bit:
var gettemplatefile = function (templatename) { var path = null; switch (templatename) { case 'header': path = 'text!../html/templates/header.tpl'; break; case 'footer': path = 'text!../html/templates/footer.tpl'; break; case 'modal': path = 'text!../html/templates/modal.tpl'; break; } return require(path); };
unfortunately, causes:
uncaught error: module name "text!blah.txt_unnormalized2" has not been loaded yet context: _
...which makes sense when realise syntactic sugar, not way make requirejs work in synchronous mode.
Comments
Post a Comment