2014-02-22 47 views
0

有產品has_many圖像。在產品編輯模板存在部分用於添加和刪除圖像如何在部分呈現後重新加載JavaScript?

_edit_images.html.erb

<% if @product.images != nil && @product.images.count > 0 %> 
    <ul id="images_index" data-update-url="<%= sort_images_url %>"> 
    <% @product.images.order(:position).each do |i| %> 
     <%= content_tag_for :li, i do %> 
     <%= image_tag i.image.url(:thumb), class: "img-polaroid" %> 
     <%= link_to image_tag('icons/remove.png'), remove_image_from_product_products_path(product_id: @product.id, image_id: i.id), remote: true, method: :get, data: { confirm: "Sure?"}, class: 'delete_item' %> 
     <% end %> 
    <% end %> 
    </ul> 
<% end %> 
<a class="btn btn-default" id='add_image' href="#add_image_form"><span class="glyphicon glyphicon-plus"></span></a> 
<%= form_tag '/admin/images', remote: true, multipart: true, id: 'add_image_form' do %> 
    <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>" /> 
    <input type="hidden" name="product_id" value="<%= @product.id %>" /> 
    <br><%= label_tag 'name', 'Image title' %> 
    <%= text_field_tag 'title', '', id: "add_image_title", class:'form-control' %><br> 
    <%= label_tag 'name', 'Выберите файл' %> 
    <%= file_field_tag 'file', class:'form-control'%><br><br> 
    <button type="submit" class="btn btn-primary">Add image</button> 
<% end %> 

表單調用圖像控制器創建行動

def create 
    image = Image.create(title: params[ :title ], image: params[ :file ]) 
    @product = Product.find_by id: params[ :product_id ] 
    @product.images << image 
    respond_to do |format| 
     format.html { redirect_to admin_products_path } 
     format.js { render '/products/edit_images' } 
    end 
    end 

圖像後被添加並拖延JavaScript不起作用。任何人都可以提出一種方法來重新渲染部分後的JavaScript?

UPDATE images.js.coffee

jQuery -> 
    $("a#add_image").on "click", (e) -> 
    $("form#add_image_form").toggle() 
    e.preventDefault() 

    $('div.actions ul#images_index').sortable 
    axis: 'y' 
    update: -> 
     $.post($(this).data('update-url'), $(this).sortable('serialize')) 
+0

您的JS的外觀如何?你使用'on()'附加你的事件處理程序嗎? – steakchaser

回答

0

答案很簡單。在頁面更新上設置事件監聽器可解決問題

images_update = -> 
    $("#add_page_image").on "click", (e) -> 
    $("form#add_image_form").toggle() 
    e.preventDefault() 

    $('#page_images_index').sortable 
    axis: 'y' 
    update: -> 
     $.post($(this).data('update-url'), $(this).sortable('serialize')) 

$(document).on 'page:update', -> 
    images_update()