【问题标题】:Updating various DOM elements after best_in_place updatebest_in_place 更新后更新各种 DOM 元素
【发布时间】:2013-01-31 23:18:43
【问题描述】:

在使用 best_in_place 更新 DOM 元素后,我在表中有各种值需要更新。在最佳就地更新后,如何触发诸如“create.js.erb”之类的名为“update.js.erb”的javascript操作?

例如,我有一张商品价格表,我需要在用户更新单个商品数量后更新该表的“总计”字段。

【问题讨论】:

    标签: ruby-on-rails-3 best-in-place


    【解决方案1】:

    我见过很多人问这个问题,但还没有找到满意的解决方案。我发现最好的方法是创建一个 javascript 函数,在 ajax:success 之后监视特定 DOM 元素的更新,然后使用 jQuery 更新指定的 DOM 元素。

    在要更新的项目的控制器中,我打包了一个 JSON 响应,其中包含我的 javascript 更新 DOM 元素所需的所有信息。

    您会看到我还将新表格行的部分呈现为 HTML 字符串,并将此字符串与 JSON 响应一起传递。

    ___Item Controller_____
    
        respond_to do |format|
      if @item.update_attributes(params[:item])
    
        #json response variables to refresh table row after update
        id = [@item]  
        new_row = render_to_string('items/_item.html', :layout => false, :locals => { :item => @item })
        #----------json-variables-----------#
    
        format.json { render :json => { new_row: new_row, id: id, :status => 200 }}
        format.js   
      else
        format.json { render :json => @item.errors.full_messages, :status => :unprocessable_entity }
        format.js
      end
    end
    

    然后在与页面一起加载的 .js 文件中(如 application.js),我包含一个函数,用于监视要更新的具有“row_class”类的表行。

    $(document).ready(function(row_class, row_id_prefix){
    
    $("." + row_class).on("ajax:success",function(event, data, status, xhr){
        var parsed_data = jQuery.parseJSON(data); //parses string returned by controller into json object
    
        var id = parsed_data["id"];
        var new_row = parsed_data["new_row"]; //this is an html string that replaces the existing table row
    
        $('tr#' + row_id_prefix + id).replaceWith(new_row);
        $('tr#' + row_id_prefix + id).effect('highlight');
        $('.best_in_place').best_in_place(); //activates in-place-editing for newly added content.      
    }));        
    

    您可以修改 jQuery 来更新您需要的任何 DOM 元素。此外,如果您需要在对象上调用 ruby​​ 方法的结果(例如人性化总计、税收总计等),您可以将这些定义为控制器中 JSON 对象中的变量。

    如果 best_in_place 最终会触发(在这种情况下)items/update.js.erb 脚本,那将是最好的,但它看起来不像在路线图上。

    【讨论】:

    • 考虑到我需要以不同的方式更新某些页面,这令人沮丧……像这样制作一个包罗万象会破坏其他页面。 :(
    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2014-10-19
    • 2014-02-11
    • 2021-08-24
    • 2015-03-29
    • 1970-01-01
    • 2016-04-26
    相关资源
    最近更新 更多