Stimulus Discourse

Rails stimulus dynamic modal need feedback

:white_check_mark: status : my solution work
:icecream: object is check with the community if my solution could be improved

Hi i have set up a solution with stimulus to inject select2 to an input within a dynamic modal rendered inside a partial.

My setup

  1. the gem file
    ruby ‘2.7.0’
    gem ‘rails’, ‘6.0.3.1’

  2. package.json
    “stimulus”: “^1.1.1”,

modal_product_form.html.erb

    <div 
       data-controller="registrations" 
       class="modal fade" 
       id="modalCreateProduct" 
       tabindex="-1" 
       role="dialog" 
       aria-hidden="true">
      <div class="modal-dialog modal-dialog-vertical d-flex" role="document">
        <div class="modal-content" id="CreateProduct">
            <%# the form is injected her %>
        </div>
       </div>
     </div>

this input below is a part of the form but all are injected inside the modal_product_form.html.erb

    <%= f.grouped_collection_select :product_sub_category_id, 
      ProductCategory.all, 
      :product_sub_categories, 
      :title, 
      :id, 
      :title, 
      {
          required: true,
          autofocus: 'true', 
          class: 'form-control'
          },
      
      class: 'form-control', 
      data: {
            target: 'registrations.select88' } %>

the controller in charge of that task

    import { Controller } from 'stimulus';
    import { initSelect88 } from '../admin/select2/init_select_product_sub_cat';

    export default class extends Controller {
      static targets = [ 'select88'];
      connect() {
        this.init();
      }

      init() {
        var OpenProductCreatorModal = document.querySelectorAll(
          '.trigerProductModal'
        );
        var goBabyGo = () => {
          initSelect88(this.select88Target, {
            width: '100%',
          });
        };
        if (OpenProductCreatorModal) {
          OpenProductCreatorModal.forEach((button) => {
            button.addEventListener('click', function (e) {
              setTimeout(goBabyGo.bind(null, this), 500);
            });
          });
        }
      }
    }

initSelect88 method

    import $ from 'jquery';

    import 'select2';

    const initSelect88 = (selector, options = {}) => {

    $(selector).select2(options);

    };

    export { initSelect88 };

result

conclusion

I would like to know how can i increase my controller performance and if I’m using well the logic, care all , Viny