How to bind to an html attribute when the innerhtml itself is already generated dynamically?

Viewed 161

To start off, this is my index.html:

<template>
    <div class="panel" innerHtml="${renderedPanel}"></div>
</template>

The innerHtml is generated once the page is rendered and can end up being something like this:

<div class="panel au-target" au-target-id="294">
   <div>
      <button class.bind="classList">this is a button</button>
   </div>
   <div>
      <img src="image.png">
   </div>
</div>

Now let's say I have this code in my script:

public classList = 'btn btn-success';

setTimeout(x => {
   this.classList= 'btn btn-warning';
},5000);

I'd expect the button to change after 5 seconds, but it won't. And in fact it won't even have any style to it because it doesn't seem to be able to bind to classList from the beginning. Aurelia is only binding to the initial HTML and not the one generated by the string I have that replaces innerHtml like so:

this.renderedPainel = this.renderedPainel.replace('$' + i + '$', '<button class.bind="test">Ok</button>');

Extra clarification: The timeout will happen only if I'm dealing with a slideshow and I will go through each image replacing the image in the html, so instead of replacing 'class' I actually need to replace the 'src' of the image without refreshing all of the other html because I have videos that need to continue playing. The $i$ is simply the index of the widget I am replacing.

Any clues on how to go about this?

2 Answers

Why don't you load your script on window.load, so that your script will be executed after all resource in the document has loaded.

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

window.onload = function() {

  public classList = 'btn btn-success';

  setTimeout(x => {
    this.classList= 'btn btn-warning';
  },5000);

}

UPDATE:

The only difference would be you have to change the src of the image on condition of slideshow, and instead of changing the class now you will have to change the src and it will load the new image when executed.

window.onload = function() {

  public classList = 'btn btn-success';

  //Assuming you have some logic to determine if you're in a slide show
  if(slideShow){
    setTimeout(x => {
      this.src = newSrc;
    },5000);
  }
}
Related