所以我找到了一个更持久的解决方案,并想与其他人分享我的做法。
我创建了一个仅实例化一次并在整个应用程序中传递的 Context 对象。看起来是这样的:
define([
'jquery',
'handlebars'
], function($, Handlebars) {
this.ctx = this.ctx || new function(options) {
if( typeof options === 'undefined' ) options = {};
/**
* introducing a _this variable that holds scope to the base object.
*/
var _this = this;
/**
* Keeps track of whether the Context has been initialized or not,
* prevents double initialization.
*/
var initialized = false;
var initHelpers = function() {
Handlebars.registerHelper('ifeq', function(v1, v2, options) {
return (v1 === v2) ? options.fn(this) : options.inverse(this);
});
}
this.init = function(options) {
if( initialized ) {
console.log('Prevented an attempt at initializing the Context object twice.');
return;
}
/* Setting the debug variable, look at the declaration above in the implementation
* for more information about this. */
debug = options.debug || false;
/**
* Initializing the Handlebars helpers, necessary for the template rendering.
*/
initHelpers();
}
// Functionality for the template caching methods. //
var hbsTemplates = {};
this.getTemplate = function(name, templateHtml) {
return hbsTemplates[name] || function() {
var compiledTemplate = Handlebars.compile(templateHtml);
hbsTemplates[name] = compiledTemplate;
return compiledTemplate;
}();
}
}
return this.ctx;
});
我们也必须尽快启动它。
Context.init({
/* Options */
});
当我创建一个主干视图时,我声明了以下变量:
template: Context.getTemplate('mywidget.mytemplate', FloorViewTemplate),
注意作为第一个参数传递的字符串。这是用来引用Context对象中HashMap中的模板的,我用文件夹结构来表示。在这种情况下,它是 mywidget/mytemplate.hbs,表示为 mywidget.mytemplate
记住此时 Context 对象已被作为任何其他类型获取
define([
'Context'
], function(Context) {
});
最后,我们得到模板并提供我们的参数。
var html = this.template({
arg1: 1,
arg2: 2
});
现在只需将 html 添加到 DOM 即可。
这很好用。如果有人对如何更有效地执行此操作有任何其他想法,请编辑答案。