开发者

How to run some code only once in view

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()'开发者_C百科 %>

No matter how many time I call the '_comment.erb', the code inside 'run_once' will be run only once. What shall I do?


This is probably not the best solution to your problem, but creating a helper that will yield only once isn't too much trouble:

Helper

def output_once(name, &block)
    @output_once_blocks ||= []
    unless @output_once_blocks.include?(name)
        @output_once_blocks << name
        concat(capture(block), block.binding)
    end
end

Usage

<% output_once :define_aaa do %>
    Your stuff here
<% end %>


<% if !@once_flag && @once_flag=1 %>
  <script>
  function aaa() {}
  </script>
<% end %>


Test to see if the function has already been defined. If not, define/run it

   <script type="text/javascript">
   /*<![CDATA[*/
      if (!aaa) {
        function aaa() {}
      }
   /*]]>*/
    </script>


Try something like this

In your layout create a hidden textfield called 'flag' and make it default value as 0

(make sure you dont include this in your partial)

in your partial script

check that value and if it is != 1 execute your function

This is not a solid solution, but since your logic needs some flag to trace the number of executions this will be a workaround

cheers, sameera


Hmm, if you want to define stuff once, You can just define another partail.

Define javascript in and render _comment.erb partial multiple times here. It should take care of both issues.


As far as I know, there no function like "run_once" available so you either have to write it yourself or handle your code another way. For javascript just define it in your application.js file and then you can call it whenever you want. If it is ruby code then put it in your application helpers and for HTML it really should be a partial.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜