hotwired / stimulus

A modest JavaScript framework for the HTML you already have
https://stimulus.hotwired.dev/
MIT License
12.62k stars 418 forks source link

Calling application.start multiple times #272

Closed hopsoft closed 4 years ago

hopsoft commented 4 years ago

I'm building a library on top of Stimulus and am wondering if it's safe for me to call application.start in my library code? Here's an example of what my library is doing.

import { Application } from 'stimulus';
const application = Application.start();
application.register('example', MyLibraryController);

Note that consumers of my library will be importing it into their Rails applications.

import 'example'; // imports the lib code from above

You can view the actual library code here: https://github.com/hopsoft/stimulus_reflex/blob/hopsoft/declarative-reflexes/javascript/stimulus_reflex.js#L92-L93

Wondering if what I'm doing is permissible or if there's a better way to accomplish what I'm after?

javan commented 4 years ago

Yes, application.start() is safe to call multiple times. It's essentially a no-op after calling it once.

It's worth noting that Application.start() is not the same thing. It creates and starts a new application instance so calling it multiple times might be undesirable. https://github.com/stimulusjs/stimulus/blob/bd20cf681c11e542f5caf8e6910352fa719c8c55/packages/%40stimulus/core/src/application.ts#L14-L18

Whether or not your library should start its own application instance is up to you. I haven't looked closely at your code, but I suspect you could export a controller class that consumers register with their own application. There's nothing wrong with having multiple applications running though. Hope that helps!