symfony / stimulus-bridge

Stimulus integration bridge for Symfony projects
https://symfony.com/ux
75 stars 15 forks source link

Fixing problem of registering a lazy multiple controller repeatedly #28

Closed weaverryan closed 3 years ago

weaverryan commented 3 years ago

Fixes #27

This would happen if you had multiple data-cotroller="ABC" on page load. All 3 would re-register the real controller, causing the real controller to be connected (and likely initialized) as many times as there were data-controller elements on the page.

The fix is a bit complex. In initialize(), we ask Stimulus for an array of ALL controllers instances it has so far. So, for the very first controller object that's created, this is empty. For the 2nd controller, the array holds 1 item (the previous controller). We loop over the "already existing controllers" and try to see if there are any that match this identifier AND are a lazy controller (__stimulusLazyController). If we find even one, we can safely assume that that lazy controller is already performing the import(). I believe that Stimulus controllers are instantiated in a synchronous process (but this is an assumption) and so we wouldn't hit any race conditions.

Tested on a real project.

Cheers!

tgalopin commented 3 years ago

Thanks Ryan.