Ad

Rails 4 - Event To Run Code After A Partial Is Rendered

I have a js.erb file that is called with ajax through a controller action. The js.erb file renders a partial. Inside the partial is a data attribute that is generated based from the model. I need a way to run code only after the partial is rendered because the code is using information in the data attribute.

items_controller.rb

  def remove_tag
    @item = Item.find_by_id(params[:id])
    //code to remove tag from item
    @item.save
    respond_to do |format|
      format.js
      @item.reload
    end
  end

remove_tag.js.erb

$("#taglist").html('<%= escape_javascript(render partial: "items/tag_list", locals: {item: @item}) %>');
//the code below needs to be run after the above partial is rendered
$('#add-tag').rules("add", {
  tagUniqueness: $('#taglist').data('tag-list').split(', ')
});

_tag_list.html.erb

<div id="taglist" data-tag-list="<%= item.all_tags_list %>">
  //more html
</div>

The way it is now, the .rules method is using html data that was there before the partial updates it.

Ad

Answer

To convert hashes or arrays from Ruby to javascript you can use .to_json as JSON basically is a subset of javascript.

$('#add-tag').rules("add", {
  tagUniqueness: <%= js @badge.all_tags_list.to_json %>
});
Ad
source: stackoverflow.com
Ad