简体   繁体   中英

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.

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 %>
});

This type of functionality would lend itself to callbacks in javascript/jquery...

A callback function is executed after the current effect is 100% finished.

We used callbacks for executing functions after ajax loads (which had to remain asynchronous). They are highly effective if you can get them to work.

There's a great reference here :

$("#taglist").html('<%= escape_javascript(render partial: "items/tag_list", locals: {item: @item}) %>').promise().done(function(){
    $('#add-tag').rules("add", {
       tagUniqueness: <%= js @badge.all_tags_list.to_json %>
    });
});

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