javascriptcustom-elementvelosetattribute

Wix setAttribute in a forEach loop only firing once?


So I'm trying to send some data I fetched from my database to a Custom Element in Wix. To communicate, I used setAttribute and attributeChangedCallback of course.

var fetchedData = await fetchData();

fetchedData.forEach(function (item, index) {
    console.log(item, index); //output is perfect: logs every single entry there is
    $w('#customElement1').setAttribute('data', index); //This however seems to only fire once, "11" is the only value getting alerted (see below)"
})

and

attributeChangedCallback(name, oldValue, newValue) {
    if(name === 'data') {
      alert(newValue); //output: '11' expected output: '1, 2, 3, 4, 5, 6...'
    }
 }
 static get observedAttributes() {
    return ['data'];
 }

As you can see, I am sending the index of the item via I am fetching setAttribute. However, my output ist just "11", though it should be 1, 2, 3, 4, 5, 6, 7... What is the problem here? Is the attributeChangedCallback too slow to react? Or ist the setAttribute only firing once? Everything else I'm putting in the loop is firing eleven times so the loop seems to work.


Solution

  • The reason this happens is because Javascript is single threaded. While your code runs, nothing else can run, including callbacks. So the only time the callback has a chance to run at all is when your code finished running, that is after the loop already ended.

    There are many resources explaining how the event loop works in more details, for instance I would recommend this video: https://youtu.be/cCOL7MC4Pl0