mardi 16 février 2016

Rails 3 upgrade : Call javascript function from js.erb with an array as parameter

Upgrading an old Rails application, I want to switch from prototype to Jquery, with unobstrusive javascript.

I have a javascript function js_avancements defined in public/javascripts/application.js (this function will move to another js file when I will switch to assets pipeline mode).

function js_avancements (nb_bars, bars_values, bars_names) {
    // test code
    alert(nb_bars);
    for (var i=0; i<nb_bars; i++) {
        alert(bars_names[i] + " : " + bars_values[i].toString());
    }
}

My old function in controller (Rails 2 / prototype) is

def avancements
  # Here I get values from DB
  # nb_bars = integer
  # bar_values = array of integers
  # bar_names = array of strings

  render :update do |page|
    page.replace_html "menu_avancement", :partial => "menu_avancement"
    page.replace_html "show_avancement", :partial => "show_avancement_clean"
    page.call 'js_avancements', nb_bars, bar_values, bar_names
  end
end

The new version (Rails 3 / JQuery)
In controller :

def avancements
  # Here I get values from DB
  # @nb_bars = integer
  # @bar_values = array of integers
  # @bar_names = array of strings
  # Values for test
  @nb_bars = 4
  @bars_values = [10,17,12,8]
  @bars_names = ['Aaa', 'Bbb', 'Ccc', 'Ddd']

  respond_to do |format|
    format.js { render "update_avancements" }
  end
end

My view (update_avancements.js.erb)

$('#menu_avancement').html('<%= escape_javascript(render(:partial => 'menu_avancement')) %>');
$('#show_avancement').html('<%= escape_javascript(render(:partial => 'show_avancement_clean')) %>');
$(document).ready(function() {
  js_avancements(<%=@nb_bars%>, <%=@bars_values%>, <%=@bars_names%>);
});

I can't get values from arrays (bar_values & bar_names) in my javascript function. If I call my javascript function with integer or string parameters only, all is working but with array nothing happens.

What am I doing wrong ? Thanks for your help.

PS : sorry for my English, you are welcome to correct it !

Aucun commentaire:

Enregistrer un commentaire