How to run some code only once in view
Posted
by Freewind
on Stack Overflow
See other posts from Stack Overflow
or by Freewind
Published on 2010-06-14T14:20:45Z
Indexed on
2010/06/14
14:22 UTC
Read the original article
Hit count: 365
ruby-on-rails
|ruby
I have a partial view called '_comment.erb', and it may be called by parent many times(e.g. in a loop). The '_comment.erb' looks like:
<script>
function aaa() {}
</script>
<%= comment.content %>
<%=link_to_function 'Do', 'aaa()' %>
You can see if the '_comment.erb' be called many times, that the javascript function 'aaa' will be re-defined many times. I hope it can be define only once, but I don't want to move it to parent view.
I hope there is a method, say 'run_once', and I can use it like this:
<%= run_once do %>
<script>
function aaa() {}
</script>
<% end %>
<%= comment.content %>
<%=link_to_function 'Do', 'aaa()' %>
No matter how many time I call the '_comment.erb', the code inside 'run_once' will be run only once. What shall I do?
© Stack Overflow or respective owner