Access Stimulus controller from outside


#1

Hello

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: https://i.gyazo.com/a078ac9fc059007236fced25cd71d871.mp4

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.
Gif: i.gyazo.com/692d8ccdf5bed7ea79e508e50ae680cd.mp4

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.

Andrew


#2

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 {
            controller.reset();
          }
        }