2013-10-25 28 views
0

我想使用Require.js文本加載用於主幹視圖的外部HTML模板!插件並製作模板路徑自定義(從「模板」屬性獲取模板路徑)。問題是 - 模板異步加載和渲染我還沒有它。這裏是我的代碼:Backbone.js - 使用Require.js文本插件預裝外部模板

自定義視圖

define([ 
    'views/abstract/base-view', 
], function (BaseView) { 

    var AppView = BaseView.extend({ 

     el: '#app-view', 

     template: 'app-view', 

     initialize: function() { 

      this.on('template:loaded', this.render, this); 

      BaseView.prototype.initialize.apply(this, arguments); 

     }, 

     render: function() { 

      this.$el.empty(); 

      var html = this.template(); 

      this.$el.html(html); 
     } 
    }); 

    return AppView; 

}); 

和抽象的視圖繼承

define([], function() { 

    var AbstractView = Backbone.View.extend({ 

     initialize: function(){ 
      this.setTemplate(); 
     }, 

     setTemplate: function(){ 
      var that = this; 
      require(['3p/text!templates/' + this.template + '.tpl'], function(tpl) { 
       that.template = _.template(tpl); 
       that.trigger('template:loaded'); 
      }); 
     } 
    }); 

    return AbstractView; 

}); 

它的工作原理,但我不喜歡聽「模板:加載」事件呈現。有什麼建議麼? 謝謝!

回答

0

我有同樣的問題。 爲了避免異步行爲,除了在某些文件中添加動態請求並將其加載之前,沒有其他方法。

我做了類似的注射。我加載了一個require所有的動態模板,並在共享字典中放入了模板的路徑。然後我使用_.template(require(inject [「templateNAME」])),我現在得到模板。

的想法是一樣的東西了下:

define(["require"], function (require) { 
    require(["text!path/of/the/template", 
      ... ]); 

    window.inject = {}; 
    inject.templateNAME = "text!path/of/the/template"; 

則可以使用這樣的事情:

var tpl = require(inject[this.templateName]); 
this.template = _.template(tpl); 
相關問題