2013-02-06 59 views
0

我在這裏找到了this example這裏介紹瞭如何使用HBS插件來管理模板。這似乎是一個很好的解決方案。 @machineghost建議使用RequireJS包含如下模板:骨幹網模板:使用HBS動態切換模板

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,我不確定。建議任何人?

+0

我的意思是先定義上述說法。 – sehummel

回答

1

初步說明:

  • require.js不允許在一個模塊定義的參數,定義接受一個依賴陣列和一個定義函數:

    define(['dep1', 'dep2', ...], function(dep1, dep2) { 
    }) 
    
  • 我不會定義視圖,實例化它並在同一模塊中注入其el,但可隨意混合並匹配到您的口味

讓我們從一個模塊開始定義一個默認模板一個簡單的觀點,讓我們說的意見/ 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(['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 
    }); 
}); 

創建與被覆蓋的默認模板一個新的類,你會定義一個新的模塊(的意見/ 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; 
}); 
+0

這應該有效。謝謝,@nikoshr。 – sehummel