2014-10-16 42 views
5

從流星0.9.4開始,定義模板。 MyTemplateMyHelperFunction()不再有效。從模板的上下文中調用另一個助手的助手(流星0.9.4)

我們不推薦使用Template.someTemplate.myHelper = ...語法來支持Template.someTemplate.helpers(...)。使用較舊的語法仍然有效,但會向控制檯輸出棄用警告。

這對我來說似乎很好,因爲它(至少)會保存一些錯誤輸入和重複的文本。不過,我很快就發現,我構建Meteor應用程序的方式依賴於這個新版本已棄用的能力。在我的應用程序中,我一直使用舊的語法定義助手/函數,然後從其他助手調用這些方法。我發現它幫助我保持代碼清潔和一致。

例如,我可能有這樣的控制:

//Common Method 
Template.myTemplate.doCommonThing = function() 
{ 
    /* Commonly used method is defined here */ 
} 

//Other Methods 
Template.myTemplate.otherThing1 = function() 
{ 
    /* Do proprietary thing here */ 
    Template.myTemplate.doCommonThing(); 
} 

Template.myTemplate.otherThing2 = function() 
{ 
    /* Do proprietary thing here */ 
    Template.myTemplate.doCommonThing(); 
} 

但這似乎並沒有提供新方法流星建議(這讓我覺得我錯了一直以來)。我的問題是,在模板的助手之間共享通用模板特定邏輯的首選方式是什麼?

+0

我意識到這仍然是一個有效的問題,因爲測試平臺最好能夠調用模板助手。否則,你最終會不必要地重寫你的應用程序... – MrMowgli 2015-02-16 02:40:26

+0

你可能會覺得這個答案有用:https://stackoverflow.com/questions/27755891/meteor-what-is-spacebars-kw-hash-object#answer-27756461 – 2015-09-25 16:25:29

回答

3

對不起,如果我是沉悶的,但你不能聲明函數作爲一個對象,並將其分配給多個助手?例如:

// Common methods 
doCommonThing = function(instance) // don't use *var* so that it becomes a global 
{ 
    /* Commonly used method is defined here */ 
} 

Template.myTemplate.helpers({ 
    otherThing1: function() { 
     var _instance = this; // assign original instance *this* to local variable for later use 
     /* Do proprietary thing here */ 
     doCommonThing(_instance); // call the common function, while passing in the current template instance 
    }, 
    otherThing2: function() { 
     var _instance = this; 
     /* Do some other proprietary thing here */ 
     doCommonThing(_instance); 
    } 
}); 

順便說一句,如果你發現你不斷重複跨多個模板相同的幫手,它可以幫助使用Template.registerHelper,而不是分配相同功能的多個地方。

+0

這個緊密耦合你的代碼。所有依賴於doCommonThing()的東西都必須知道它存在,以及它是如何被調用的。這是乾的,但耦合。 – 2015-09-25 16:09:26

+0

你可能會覺得這個答案有用:https://stackoverflow.com/questions/27755891/meteor-what-is-spacebars-kw-hash-object#answer-27756461 – 2015-09-25 16:25:15

相關問題