骨干模板:使用HBS动态切换模板

时间:2013-02-06 16:06:18

标签: backbone.js requirejs

我在这里找到了this example如何使用HBS插件来管理模板。这似乎是一个很好的解决方案。 @machineghost建议使用RequireJS来包含这样的模板:

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语句,该语句会告诉Backbone使用哪个模板路径?我是Backbone的新手,特别是RequireJS,我不确定。建议任何人?

1 个答案:

答案 0 :(得分:1)

初步说明:

  • require.js不允许模块定义中的参数,define接受依赖数组和定义函数:

    define(['dep1', 'dep2', ...], function(dep1, dep2) {
    })
    
  • 我不会定义视图,实例化它并在同一个模块中注入它,但随意混合搭配你的味道

让我们从定义带有默认模板的简单视图的模块开始,假设 views / templated.js

define(['backbone', 'hbs!path/to/defaultTemplate'], 
    function(Backbone, defaultTemplate) {

    var MyNewView = Backbone.View.extend({
        template: defaultTemplate,

        initialize: function(opts) {
            opts = opts || {};

            // use the template defined in the options or on the prototype
            this.template = opts.template || this.template; 
        }
     });

     return MyNewView;
});

现在您只需要使用require:

来提取视图定义和可选模板
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

define(['views/templated', 'hbs!path/to/anotherTemplate'], 
    function(MyNewView, anotherTemplate) {

    var AnotherNewView = MyNewView.extend({
        template: anotherTemplate
     });

     return AnotherNewView;
});

最后,您始终可以通过直接指定新值来更改给定实例上的模板。

var v = new MyNewView();
v.template = tpl;

模拟视图层次结构的小提琴:http://jsfiddle.net/nikoshr/URddR/

回到你的代码,你的块可能看起来像

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;
});