Is StimulusJS good for this kind of project?

Hi all,

I am working on a Phoenix (elixir) project which is a CRUD admin.
I need to augment it with some Javascript and I am evaluating Stimulus.

This is an example of the kind of js behaviour I have to add:

  • In the create/update form of a resource A, add/remove fieldsets for n related resource B
  • The related resource B has a select field where the options depend on each other, so I need some state at the level of A

Hope this is clear, I’ll try explain it better if needed.

Thank you

You bet, Stimulus (and maybe some clever use of turbo_stream elements) should make this work well.

For dynamically adding more resource B fieldsets, you might want to check out Matt Swanson’s tweet about the approach he found, which I thought was nice and lean.

1 Like

Thank you.
I am not exactly sure what Turbo is, but it seems like Phoenix LiveView, which is not an option for me at this point.

What does it take in terms of boilerplate to give Stimulus a spin?
Can I just import a stimulus controller in any js module and “run it”?

The official documentation starts with a link to a template project, which is not ideal (I would love to try it in my current real project).

Thank you

Without knowing the structure of your project, it’s hard to tell what’s the best approach for you, but you could just try the “Using without a build system” section from the stimulus handbook to start with and write the script inline, in your template. Then you could switch to external script files (javascript entrypoints to be bundled or whatever way you prefer) later/if needed.

Since you attach the stimulus controllers with html data attributes, there’s very little boilerplate.

1 Like

I am using esbuild, the default bundler in Phoenix.
I have only one entry point for the whole application, I only need to call Application.start() and then register the controllers IIUC.

IIUC 2: I am basically doing the same thing with functions and javascript, this is what my application looks like now:

import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";
window.ComponentA = ComponentA;
window.ComponentB = ComponentB;

const components = document.querySelectorAll("[data-component]");
components.forEach((el) => {
  const componentName = el.dataset.component;
  const fn = window[componentName];
  if (typeof fn === "function") fn.apply({}, [el]);
  else console.warn(`Can't initialize the component named '${componentName}'.`);
});

I was curious about Stimulus because it seems very similar to that approach, with bell and whistles.

I will give it a try!

Thank you