visioncode
visioncode

Reputation: 97

Alpine JS change value from dynamic modal

What is the best practice for this example below? I open a dynamic modal and within this modal, I want to change values from another x-data scope. I'm still confused how I can access (and modify) the count value from within my modal.

<html>
    <body x-data>
        <button id="load-modal">This load/open my modal</button>
        
        <div x-data="{ count: 0 }">
            <button @click="count++">Increment</button>
         
            <span x-text="count"></span>
        </div>
        
        <div class="modal">
            <!-- dynamic inserted HTML -->
            <a class="btn" @click="count++">This should increment the count above</a>
        </div>
    </body>
</html>

Upvotes: 0

Views: 2456

Answers (1)

Dauros
Dauros

Reputation: 10557

You have a few options. The first one is using events. The sibling button dispatches a "count increment" event, the counter component listens to it and acts accordingly. Note the .window modifier that is required for event propagation.

<div x-data>
  <div x-data="{ count: 0 }" @increase-count.window="count++">
    <button @click="count++">Increment</button>
    <span x-text="count"></span>
  </div>

  <div class="modal">
    <a class="btn" @click="$dispatch('increase-count')">Increment from outside</a>
  </div>
</div>

The second options is to use the global store.

<div x-data>
  <div>
    <button @click="$store.count++">Increment</button>
    <span x-text="$store.count"></span>
  </div>

  <div class="modal">
    <a class="btn" @click="$store.count++">Increment from outside</a>
  </div>
</div>

<script>
document.addEventListener('alpine:init', () => {
  // Single value store definition
  Alpine.store('count', 0)
})
</script>

Here we use the simplified syntax for the count, however you can add methods to a store as well, e.g. a reset function.

For this simple counter I would use the event method. If you want to add more logic to the counter, I would choose the global store and put the corresponding logic there.

Upvotes: 2

Related Questions