2014-10-18 91 views
1

按照我所知,marionette.template接受jquery selectorcompiled template string如何将函数分配给marionette.template

如果我写这样以下列方式代码,做工精细

exports.ProductInfoView=Backbone.Marionette.ItemView.extend({ 
     domInfo:{ 
      mainTemplateId:"tagProductListTpl", 
      tableTemplateId:"taginfoViewTpl" 
     }, 
     template:commomFunctions.templateCompilation("tagProductListTpl",""), 
     onRender:function(){ 
      this.templatingProductInformation(); 
     }, 
     modelEvents:{ 
      "change:currentJson":"templatingProductInformation" 
     }, 
     templatingProductInformation:function(){ 
      console.log(this.el); 
      //this.el.innerHTML=commomFunctions.templateCompilation(this.ui.mainTemplateId,""); 
     } 
    }); 

注:commonFunctions.templateCompilation()接受templateId作为第一个参数,作为data第二个参数。它将编译handlebars template并返回编译模板。

如果我将该返回值分配给template,则正常工作。

我想为模板数据,所以我传递functiontemplate like in the following way.

exports.ProductInfoView=Backbone.Marionette.ItemView.extend({ 
     domInfo:{ 
      mainTemplateId:"tagProductListTpl", 
      tableTemplateId:"taginfoViewTpl" 
     }, 
     template:function(){ 
      return commomFunctions.templateCompilation("tagProductListTpl",""); 
     }, 
     onRender:function(){ 
      this.templatingProductInformation(); 
     }, 
     modelEvents:{ 
      "change:currentJson":"templatingProductInformation" 
     }, 
     templatingProductInformation:function(){ 
      console.log(this.el); 
      //this.el.innerHTML=commomFunctions.templateCompilation(this.ui.mainTemplateId,""); 
     } 
    }); 

这种方式也工作正常,如果你观察我硬编码templateId("tagProductListTpl")内function.But我不希望这样的。我想用this.domInfo.mainTemplateId而不是硬编码。这样它不能正常工作。

这是抛出错误。我知道它超出了范围。但我怎么能实现这一点。

任何人都可以帮助我。

谢谢。

回答

1

我会建议你重写Marionette.TemplateCache.prototype.compileTemplate,它负责模板编译。看看this的帖子,有几乎相同的问题。

Marionette.TemplateCache.prototype.compileTemplate = function (yourRawTemplate) { 
     // In case if template is function 
     if (_.isFunction(yourRawTemplate)) { 
      return yourRawTemplate; 
     } else { 
      return Handlebars.compile(yourRawTemplate); 
     } 
}; 

如果您从远程服务器加载模板文件,您还需要重写Backbone.Marionette.TemplateCache.prototype.loadTemplate。这里的例子:

Marionette.TemplateCache.prototype.loadTemplate = function (templateId) { 
    var template = '', 
     templateUrl = 'path_to_your_template/' + templateId + '.html'; 

    // Loading template synchronously. 
    Backbone.$.ajax({ 
     async : false, 
     url  : templateUrl, 
     success : function (templateHtml) { 
      template = templateHtml; 
     } 
    }); 

    return template; 
};