简体   繁体   中英

javascript on a partial - ruby on rails

I have a partial that gets loaded every 3 seconds using AJAX (Prototype framework), this way:

  <script type="text/javascript">
   new Ajax.PeriodicalUpdater('content', '/shouts/update.js', { method: 'get', frequency: 1});
</script>

this is the part of the controller that loads the partial:

respond_to do |format|
    format.js {render(:partial => 'content', :locals => {:content => @last_shout.content})}
end

this is the content of the partial "_content.html.erb" :

<h2><%= content %></h2>

So far everything works great.

I want to add, that every time the partial will be reloaded, it will be fadeIn using Scriptaculous framework. I added this code to the _content.html.erb partial:

 <script type="text/javascript">
$('content').fade({ duration: 3.0, from: 0, to: 1 });
</script>

The problem was that instead of executing the code every time the partial gets reloaded, it executed it only one time. What do I need to do on order to make javascript code execute every time the partial gets loaded ?

have a look at the rjs docs ... http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper/JavaScriptGenerator/GeneratorMethods.html

you could use it with jquery using jrails ...

then instead of

{render(:partial => 'content', :locals => {:content => @last_shout.content})}

you could accomplish the same action in the associated rjs files and add some other functions.

It's simple to use , look at some example online .

I would move the fading part into the AjaxUpdater:

<script type="text/javascript">
   new Ajax.PeriodicalUpdater('content', '/shouts/update.js', { method: 'get', frequency: 1, onComplete: function() {$('content').fade({ duration: 3.0, from: 0, to: 1 });}});
</script>

It could be a matter of timing (the text is replaced before onComplete is called, but the script within the text is evaluated earlier.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM