2014-05-14 2 views
0

내 응용 프로그램에는 제품 및 색상이라는 두 가지 모델이 있습니다. 제품의 색상이 다양하며 nested_form gem을 사용하여 제품 양식에서 색상을 제품에 동적으로 추가하고 있습니다.nested_form gem을 사용하여 동적으로 생성 된 양식을 수정하기위한 javascript 함수 트리거

# app/views/products/_form.html.erb 
<%= nested_form_for @product do |f| %> 

    <%= f.label :name %> 
    <%= f.select(:name, options_for_select(@product_names), { include_blank: true }) %> 

    <%= f.fields_for :colors do |c| %> 
    <%= render "color_fields", :f => c %> 
    <%= c.link_to_remove "Remove this color" %> 
    <% end %> 

    <%= f.link_to_add("Add a color", :colors) %></p> 

<% end %> 

그리고 :

# app/views/products/_color_fields.html.erb 
<%= f.label :color %> 
<%= f.select(:color, options_for_select(@color_options, :selected => @color_options.first), {}, { :class => 'color_select' }) %> 

는 게다가, 색상 선택기에서 색상을 선택 양식을 변환하기 위해 jquery-simplecolorpicker-rails gem을 사용이 내이다.

서식 선택

다음과 같은 라인 색상 선택기로 변환된다 : 2.times { @product.colors.build } : 내 컨트롤러에서
# app/assets/javascripts/products.js.coffee 
$ -> 
    $('select[class="color_select"]').simplecolorpicker({theme: 'regularfont'}) 

내가이 개 초기 색상 요소를 구축 할 수 있습니다. 이 두 색상의 선택 양식은 내 자바 스크립트 선에 따라 색상 선택기로 올바르게 변환됩니다. 그러나 "Add a color"링크를 클릭하면 새 색상 선택 양식이 색상 선택기로 표시되지 않고 일반 선택 항목으로 표시됩니다.

$('select[class="color_select"]').simplecolorpicker({theme: 'regularfont'}) 호출을 어떻게 트리거하여 새로운 색상 선택을 만들 때마다 색상 선택 도구와 함께 표시됩니까?

답변

0

nested_form 설명서를 제대로 읽으면이 질문에 대한 답을 찾았습니다.

당신이 클릭 "이 색상을 제거"경우 nested:fieldRemovednested:fieldRemoved:colors이 발생됩니다 반면, nested:fieldAddednested:fieldAdded:colors이 발생됩니다 경우 "색상을 추가"를 클릭

. 자바 스크립트

$(document).on "nested:fieldAdded", (event) -> 
    $('select[class="t_shirt-color_select"]').simplecolorpicker({theme: 'regularfont'}) 

그리고 해당하는 것 :

그래서이 문제를 해결하기 위해 커피 스크립트는

$(document).on('nested:fieldAdded', function(event){ 
    $('select[class="t_shirt-color_select"]').simplecolorpicker({theme: 'regularfont'}) 
})