Using AlpineJS's $store magic

Using AlpineJS's $store magic

Updating DOM by just adding an entry to the global array

I was trying to explain reactiveness using AlpineJS to a colleague at work but failed to make a point which is the crux of how the DOM gets updated.

It's based on this blog post which has a demo.

I went on to explain that, by simply adding an entry (entry being an object in this case) to the array will auto-magically update the DIV container by populating the new array's element into the HTML.

So I went ahead and did the obvious - (what I thought would / should work) - push an object into the array so that I can show him that the table gets a new row inserted without the need to write a single line of DOM manipulation code.

But there lay an issue where this didn't work! I tried to add an object to the array in the browser's console! Thing is, this will work only when pushed within the AlpineJS section - within where x-data="{ data: content }" is defined. Outside of this, there's no way to access AlpineJS's variables.

Here comes in the $store magic.

It's like a global variable attached to AlpineJS's 'store' which has all the hooks to AlpineJS's functionality. It defeats the purpose of localized variables, but the only advantage of this is if you want to access variables from the outside or in the browser's console.

We basically add an event listener to when AlpineJS inititializes by document.addEventListener("alpine:init") and adding a data variable to it and a function to update the data.'global_data',
    data: content,
    push(name, description)
    {{name, description});

In the AlpineJS block we don't set the data in x-data - in this case we have it as x-data="{}"

And in the button on-click, we call the $store's global_data's push function

<button type="submit" x-on:click="$store.global_data.push(document.getElementById('name').value, document.getElementById('description').value);" class="btn btn-primary">Add</button>

I've added a lone global push function just to call it from the outside for us to test :

const push = (name, description) =>
{'global_data').push(name, description);

Basically, this is direct access to the array in the browser console :'global_data').data.push({name: 'Test N', description: 'Test DescriptionN'});

I just demoed it using a function that just does this line above to make it shorter for typing.

Demo :