Access Stimulus controller from outside


I was using Stimulus on a custom add to cart Shopify theme tweak.

Customer add to cart 2 types of products:

  1. products where quantity is 1 (normal products)
  2. products where quantity is (0.25 grams).
    Here is a video gif with the working example:

The products are added to cart using ajax and CartJS and the cart is updated automatically:
Gif: gyazo -> 6a7b01e8cfcdd5432358b662105674e9.mp4 (Sorry for the url but I can add more than 2 links in this post)

The problem is that the state of the product is not updated when changing quantities or removing the item directly from the cart. So if the cart is empty, the product still shows that there are added 4 items in cart.

What would be the best way to access the Stimulus controller and update the new product values with the ones from the cart?

Thank you very much in advance.


I was able to find a solution after more research in Github issues and this forum.
I’m posting the solution I found to my issue.

reset() {
          var controller = stimulusApp.getControllerForElementAndIdentifier(document.getElementById("addToCart-" + this.variant), "addtocart");
          if (controller == undefined || controller == null) {
            console.log('Normal Remove From Cart');
          } else {

You can add the following line to your Stimulus controller’s connect() method:

this.element[this.identifier] = this

Now, if you can get a reference to the DOM element your controller is defined on, you can easily access the internal scope of that controller from jQuery plugins, the browser console and other Stimulus controllers.