Backbone.js 主干模板:使用HBS动态切换模板
我在这里了解了如何使用HBS插件管理模板。这似乎是一个很好的解决方案@MachineHost建议使用RequireJS包含如下模板:Backbone.js 主干模板:使用HBS动态切换模板,backbone.js,requirejs,Backbone.js,Requirejs,我在这里了解了如何使用HBS插件管理模板。这似乎是一个很好的解决方案@MachineHost建议使用RequireJS包含如下模板: define(['template!path/to/someTemplate'], function(someTemplate) { var MyNewView = BaseView.extend({template: someTemplate}); $('body').append(new MyNewView().render().el); }
define(['template!path/to/someTemplate'], function(someTemplate) {
var MyNewView = BaseView.extend({template: someTemplate});
$('body').append(new MyNewView().render().el);
}
这是伟大的,除了我需要动态切换模板。以下是我的一个观点示例:
define([
'jquery',
'underscore',
'backbone',
'models/tableModel',
'collections/tablesCollection',
'views/tablesView'
], function($, _, Backbone, tableModel, tablesCollection, tablesView) {
var t = new tablesCollection(null, {url: 'applications-lab'});
return new tablesView({ collection: t, template: 'applications-lab-template', url: 'applications-lab'});
});
如您所见,在渲染视图时,我正在传递模板。我想知道的是,我是否可以将一个变量传递给define
语句,告诉主干网使用哪个模板路径?我是一个新手主干,尤其是RequireJS,我不确定。任何人的建议?初步说明:
- require.js不允许在模块定义中使用参数,define接受依赖项数组和定义函数:
define(['dep1', 'dep2', ...], function(dep1, dep2) { })
- 我不会在同一个模块中定义一个视图、实例化它并注入它的el,但可以根据您的喜好随意混合和匹配
require(['views/templated', 'hbs!path/to/anotherTemplate'],
function(MyNewView, anotherTemplate) {
// a view with the default template
var v1 = new MyNewView();
// a view with a new template
var v2 = new MyNewView({
template: anotherTemplate
});
});
要使用重写的默认模板创建一个新类,您需要定义一个新模块(views/override.js)
最后,您始终可以通过直接指定新值来更改给定实例上的模板
var v = new MyNewView();
v.template = tpl;
模拟视图层次结构的小提琴:
回到您的代码,您的块可能看起来像
require(['models/tableModel', 'collections/tablesCollection', 'views/templated', 'applications-lab-template'],
function(tableModel, tablesCollection, tablesView, tpl) {
var t = new tablesCollection(null, {url: 'applications-lab'});
var v = new tablesView({
collection: t,
template: tpl
url: 'applications-lab'
});
// or, if you prefer and you don't render in initialize
v.template = tpl;
});
我指的是上面的第一个define语句。
var v = new MyNewView();
v.template = tpl;
require(['models/tableModel', 'collections/tablesCollection', 'views/templated', 'applications-lab-template'],
function(tableModel, tablesCollection, tablesView, tpl) {
var t = new tablesCollection(null, {url: 'applications-lab'});
var v = new tablesView({
collection: t,
template: tpl
url: 'applications-lab'
});
// or, if you prefer and you don't render in initialize
v.template = tpl;
});