Run JS on turbo changes

Hello everyone!

I’m trying to rerun some js again after form submit fails, code:
function run_selectize() {
(".selectize#item_category_ids").selectize({ create: function (input, callback) { .ajax({
method: “POST”,
url: “/categories.json”,
data: { category: { name: input } },
success: function (response) {
// call callback with the new item
callback({ value: response.id, text: response.name });
},
});
},
});
}

$(document).on("turbo:load", function () {
  run_selectize();
});

$(document).on("turbo:submit-end", function (ev) {
  if (ev.originalEvent.target == document.querySelector("form#item_form")) {
    if (ev.originalEvent.detail.success) {
      $("#modal_item_form").modal("hide");
    } else {
      run_selectize();
    }
  }
});

But this doesn’t works. Any ideas? (the else condition is ok, tested before)

I’m wondering if ev.originalEvent.target should be ev.detail.formSubmission.formElement? As per:

Access the FormSubmission object with event.detail.formSubmission

From: https://turbo.hotwire.dev/reference/events

That works, I’m returning status 500 if errors, so, success its equals to false, and the else condition runs. I just fix it (temporary) with something like this:

$(document).on("turbo:before-fetch-response", function(){
  var checkExist = setInterval(function () {
    if ($('.selectize#item_category_ids').length) {
      $(".selectize#item_category_ids").selectize({
        create: function (input, callback) {
          $.ajax({
            method: "POST",
            url: "/categories.json",
            data: { category: { name: input } },
            success: function (response) {
              // call callback with the new item
              callback({ value: response.id, text: response.name });
            }
          });
        },
      });
      clearInterval(checkExist);
    }
  }, 100);
});