2011-12-18 17 views
0

在我的rails 3.1應用程序中,我添加了update.js.erb,create.js.erb和destroy.js.erb模板來處理JavaScript請求,並且一切都很好。這些代碼都有類似的代碼塊,需要調用它來更新DOM的各個部分。如何/在哪裏創建一個jQuery/erb代碼的共享方法?

... 

// recalculate envelope total 
$('#<%= "#{dom_id @transaction.envelope} .available" %>').html('<%= "#{formatted_money @transaction.envelope.amount_available}" %>'); 

我想封裝這個邏輯,什麼是Rails的方式,使這更「幹」?

我想象什麼是這樣的:

<%= recalculate_envelope(@transaction.envelope) %> 

但我不知道這個方法應該去,以便它是共享的,每個模板,並針對不同的控制器潛在的其他模板。對於這個問題,它甚至應該返回什麼?

謝謝。

回答

0

您應該將該方法放在輔助類中。如果你想讓這個方法對所有vews都可用(不管哪個控制器),你必須把它放在類ApplicationHelper中。針對特定助手類中的特定控制器的視圖(例如,使得方法可視爲ProfileController的所有視圖的ProfileHelper)。

因此,在您的輔助類,你可以實現你的方法,例如:

class ApplicationHelper 
    def recalculate_envelope(dom_id, envelope) 
    "$('##{dom_id envelope} .available').html('#{formatted_money envelope.amount_available}');" 
    end 
end 

然後你就可以用

<%= recalculate_envelope(@transaction.envelope) %> 
+0

謝謝您訪問的方法在你的意見!我沒有意識到它是那麼簡單,但我想這就是HTML模板的助手如何工作,爲什麼不爲js呢? – 2011-12-18 23:10:20

相關問題