'How can I make Rails JS views DRY?

I have this image tag

      <div id="google_icon_div">
        <%= image_tag "google-icon.png", id: "google_icon", onclick: "test_transl(#{passed_resource}, #{passed_locales.to_json}, #{primary_resource})", remote: true%>
      </div>

And I have this JS function

<script>
  function test_transl(resource_value, locales_arr, primary_resource){
      var primary_text;
      if (primary_resource.getElementsByClassName('Polaris-TextField__Input')[0] == null) {
          primary_text = primary_resource.getElementsByClassName('note-editable')[0].innerText
      } else {
          primary_text = primary_resource.getElementsByClassName('Polaris-TextField__Input')[0].value
      }
      locales_arr = locales_arr.map(i => i.replaceAll('-','_'));
      var locales_resource_arr = locales_arr.map(i => resource_value + '_' + i);

     $.ajax({
          type: "GET",
          headers: {
             "Authorization": "Bearer " + window.sessionToken
          },
          url: "/api/translations/translate_string",
          dataType: "json",
          data: {primary_value: primary_text, short_locales_arr: locales_arr},
          success: function(result){
              for (var i=0; i<locales_arr.length; i++)
              {
                  my_div = document.getElementById(locales_resource_arr[i])
                  if (my_div.getElementsByClassName('Polaris-TextField__Input')[0] == null) {
                      my_div.getElementsByTagName('textarea')[0].value = result[i]
                      my_div.getElementsByClassName('note-editable')[0].innerText = result[i]
                      my_div.getElementsByClassName('note-placeholder')[0].innerText = ''
                  }
                  else {
                      my_div.getElementsByClassName('Polaris-TextField__Input')[0].value = result[i].replace(/['"]+/g, '')
                  }
              }
           },
         error: function (result){
              console.log(result, this.error)
         }
      })
  }
</script>

I have the same code on several other views pages with very minor differences. Is there any way I can try to make my code DRY? How can I make a single JS function and be able to parse different objects to it via onclick and not repeat the same JS code on different html.erb pages?



Solution 1:[1]

You aren't clear about the "different object" that you'd like to parse, so I'm just guessing that you mean you need to find different dom classes / elements.

Make sure your JS is not embedded in the erb, it should be in its own file in your js directory. Then in the ERB add the dom element name in a hidden filed that your JS can fetch. Like:

<span id="parseObject" style="display: none">Polaris-TextField__Input</span>

Then in your JS before your other calls, fetch the name field.

const value = document.getElementById('parseObject').value;

Then your script would look like

<script>
  function test_transl(resource_value, locales_arr, primary_resource){
      const parseObjectName = document.getElementById('parseObject').value;
      var primary_text;
      if (primary_resource.getElementsByClassName(parseObjectName)[0] == null) {
          primary_text = primary_resource.getElementsByClassName('note-editable')[0].innerText
      } else {
          primary_text = primary_resource.getElementsByClassName(parseObjectName)[0].value
      }
      locales_arr = locales_arr.map(i => i.replaceAll('-','_'));
      var locales_resource_arr = locales_arr.map(i => resource_value + '_' + i);

     $.ajax({
          type: "GET",
          headers: {
             "Authorization": "Bearer " + window.sessionToken
          },
          url: "/api/translations/translate_string",
          dataType: "json",
          data: {primary_value: primary_text, short_locales_arr: locales_arr},
          success: function(result){
              for (var i=0; i<locales_arr.length; i++)
              {
                  my_div = document.getElementById(locales_resource_arr[i])
                  if (my_div.getElementsByClassName(parseObjectName)[0] == null) {
                      my_div.getElementsByTagName('textarea')[0].value = result[i]
                      my_div.getElementsByClassName('note-editable')[0].innerText = result[i]
                      my_div.getElementsByClassName('note-placeholder')[0].innerText = ''
                  }
                  else {
                      my_div.getElementsByClassName(parseObjectName)[0].value = result[i].replace(/['"]+/g, '')
                  }
              }
           },
         error: function (result){
              console.log(result, this.error)
         }
      })
  }
</script>

Or something similar

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 trh