Alex Rivera | Logout

format.js is not manipulating dom once action caching enabled

Asked 2012-11-29T22:00:33.927
11

Note: I am presenting a logic here what I am doing.

What I am doing:

Think about the basic index action where we are listing products and with pagination. Now using remote-true option I have enabled ajax based pagination. So far things works perfectly fine. Take a look on sample code.

Products Controller:

 def index
  @products = Product.paginate(:order =>"name ASC" ,:page => params[:page], :per_page => 14)
   respond_to do |format|
     format.html # index.html.erb
     format.json { render json: @products }
     format.js
   end
 end

Index.html.erb

<h1>Products</h1>
<div id="products">
    <%= render "products/products" %> // products partial is just basic html rendering
</div>

<script>
$(function(){
   $('.pagination a').attr('data-remote', 'true')
});
</script>

Index.js.erb

  jQuery('#products').html("<%= escape_javascript (render :partial => 'products/products' ) %>");
  $('.pagination a').attr('data-remote', 'true');

So whats the problem:

Now I want to enable action caching on this. But index.js.erb file is not manipulating DOM. If I remove the remote-true functionality then things works fine with caching.

For action caching I have added this line on the top of the controller:

 caches_action :index, :cache_path => Proc.new { |c| c.params }

Any suggestions?

Update:

Problem is jquery code is not executing. From this question

I found out what's wrong. jQuery actually surround the incoming script with a so that the browser evaluates the incoming code. But the caching mechansim merely saves the code as text and when one re-req

Edit
Report

1 Answer

4

After some trial and error, I think I have a work around.

Page links

Instead of

$(function() { $('.pagination a').attr('data-remote', 'true') });

use

$(function() {
  $('.pagination a').click(function() {
    $.ajax({
      url: this.href,
      dataType: 'script'
    });
    return false;
  });
});

so response created by the app server will be run as javascript

Controller

next, change your caches_action line to

caches_action :index, cache_path: proc { |c| c.params.except(:_).merge(format: request.format) }

since ajax appends a _ params for some sort of timestamp

Hopefully this works :)

answered 2013-02-07T09:32:15.077

Your Answer