Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to refactor a functioning piece of code written in jQuery/Coffeescript for reusability
    primarykey
    data
    text
    <p>The following code works for me:</p> <pre><code> $ -&gt; $("[id$=\"_phase_id\"]").change(-&gt; common_prefix = "type_well_type_well_phases_attributes_" cell_pos = $(this).attr("id").match(/\d+/g) mult = "#" + common_prefix + cell_pos + "_multiplier" mol = $("#" + common_prefix + cell_pos + "_mol_percent").val() gpm = "#" + common_prefix + cell_pos + "_GPM" component_id = $(this).val() $.getJSON('/phases/' + component_id, (data) -&gt; pressure_base = 0.0 if $("#type_well_pressure_base").val() == "14.65" pressure_base = data.base1 else if $("#type_well_pressure_base").val() == "14.696" pressure_base = data.base2 else if $("#type_well_pressure_base").val() == "14.73" pressure_base = data.base3 else if $("#type_well_pressure_base").val() == "15.025" pressure_base = data.base4 mult_value = parseFloat(pressure_base) $(mult).val mult_value $(gpm).val bcr_round_to(mult_value * (mol / 100.0), 4) if (mol != "") ) ).trigger "change" </code></pre> <p>This is walking through a nested form (phase_attributes) in my Rails code to call json based on a value (presure_base drop-down) selected in my parent form (type_well) and then compute a value (gpm) for the nested form. As you can see, if the phase is "changed" in the phases drop-down, I fetch the corresponding row from database and based on the value of pressure_base (14.65, 14.696, 14.73, 15.025), I compute the "gpm" value. It is all working.</p> <p>Now I am trying to put it the functionality to automatically recompute the nested form's "gpm" values when the "pressure_base" itself is changed by the user. Clearly, I have to loop through the nested rows (I know how to do it so that is no problem), and basically repeat the process again for each nested row. The only variable here is the "cell_pos". Is there any way that I can extract out a subordinate jQuery/Coffeescript function which is called from my loop repeatedly? I know how to do it in Ruby/Rails since I am quite comfortable with it, but have less experience with jQuery (even less with Coffeescript).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload