2016-10-17 24 views
0

在Dojo 1.10+中是否有一種方法可以動態地設置基於模板的小部件的templateString?如何動態設置模板字符串?

比如我想是這樣的

... 
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { 

templateString: undefined, 

constructor: function(myTemplate){ 
    var that = this; 

    //set the template 
    require(["dojo/text!" + myTemplate], function (template) { 
     that.templateString = template; 
    }); 
} 
... 

,但它是不成功的,templateString總是不確定的,因此用一個404錯誤崩潰,因爲它無法找到HTML文件。

這甚至可能嗎?

回答

2

如果只有一組有限的可以設置,你可以使用這樣的模板:

define([ 
    "dojo/_base/declare", 
    "dijit/_TemplatedMixin", 
    "dojo/text!path_to_template1.html", 
    "dojo/text!path_to_template2.html" 
], function(declare, _TemplatedMixin, template1, template2) 
{ 
    return declare([_TemplatedMixin], 
    { 
     templateToUse: 1, 

     constructor: function(params) 
     { 
      this.templateToUse = params.templateToUse; 
     }, 

     buildRendering: function() 
     { 
      switch(this.templateToUse) { 
       case 2: 
        this.templateString = template2; 
        break; 
       case 1: 
        this.templateString = template1; 
        break; 
       default: 
        this.templateString = template1; 
      }; 

      this.inherited(arguments); 
     } 
    } 
} 

我要問什麼是用例的這個,因爲我可以看到幾個備選方案是可能更好。

  • 如果模板顯着不同,爲什麼不創建單獨的小部件?您可以使用dojo提供的OOP或mixin技術在它們之間共享功能。
  • 通過傳遞給窗口構件的參數可以高度自定義單個模板。您可以將不同的元素附加到dojo連接點,或者通過將display:none樣式設置爲它們來隱藏某些元素。
+0

在調用buildRendering之後,我發現我在構造函數中設置的小部件的屬性變爲null,buildRendering除了設置可以解釋這個的模板之外還做了其他的事情? – erotavlas

+0

通常,這些屬性應該在調用buildRendering時可用。如果您可以發佈更多的代碼部分,如果您仍然遇到問題,這將非常有用。 – pgianna

+0

以及我將我的所有代碼(除了templateToUse賦值)從構造函數移動到後期創建並修復它。 – erotavlas