2015-06-25 15 views
0

我有一個視圖,它是一個木偶ItemView。我想訪問此視圖上的其他參數使用「this」內部的模板函數,但我得到它作爲未定義,我不確定爲什麼。MarionetteJS - 不能在模板函數中引用此

define(['jquery', 'hbs!templates/template', 'backbone'], 
    function ($, template, Backbone) { 
     "use strict"; 

     return Backbone.Marionette.ItemView.extend({ 

      name: "Depth", 

      el: ".card", 

      template: function(serializedModel){ 
       var self = this; // self is undefined, so I can't reference this.name, which would be Depth 

       var data = {isDepth: true, cardTitle: self.name, injectHTML: template()}; 

       .... do some stuff ... 

       return template(); 
      } 
     }); 
    } 
); 

回答

2

您可以使用下劃線的bindAll綁定模板您marionetteItem查看的這個時候它的調用。所以像這樣:

Backbone.Marionette.ItemView.extend({ 
    initialize: function(){ 
     _.bindAll(this, 'template'); 
    }, 
    template: function() { 
     //this refers to the parent object scope. 
    } 
}); 
3

您可以使用templateHelpers來訪問模板自定義變量:

templateHelpers:function(){ 
    return { 
     card_title: this.name 
    } 
} 
+0

你能詳細說明嗎?我有點新在木偶 – SoluableNonagon

+0

當然,在模板助手功能(視圖的方法)中,您可以訪問綁定到視圖對象的屬性。檢查更新的答案,這可能會給你更多的理解。現在,您可以直接在模板中訪問card_title屬性。 – Trace

+0

感謝您的更新。現在我將如何訪問模板函數中的模板幫助函數? – SoluableNonagon