How do get Aurelia to render my view after dynamically adding a custom element to the DOM?

末鹿安然 提交于 2019-12-01 14:31:03

问题


When creating a custom element in the DOM and adding a respective view model which implements bindable from the aurelia-framework, my view renders perfectly.

custom element in DOM as so:

<!-- chatbox.html -->
<template>
...    
    <ul class="chat">
        <answer name="Reah Miyara" nickname="RM" text="Hello World"></answer>
    </ul>
...
    <button class="btn" click.trigger="addCustomElement()">Add</button>
...
</template>

Aurelia's magic rendering results in various children elements associated with the custom element in the DOM, when inspecting from the browser.

The issue arises when I am attempting to dynamically add additional custom elements to the DOM using jQuery like so...

// chatbox.js
addCustomElement() { 
    $('.chat').append('<answer name="Joe Smith" nickname="JS"></answer>');
}

Invoking this method using the button (Aurelia's 'click.trigger') indeed adds the custom element to the DOM, but without the various children elements which allows the custom element to be properly rendered in the view...

How do I properly dynamically add custom elements to the DOM or tell Aurelia to process a custom element which I have added so it renders in my view?

Thanks in advance!


回答1:


I would modify as follows:

//chatbox.js
export class Chatbox {
   answers = [{
      name:'Reah Miyara',
      nickname:'RM'
   }];
   addCustomElement() {
      answers.push({
        name:'Joe Smith',
        nickname: 'JS'
      }];
   }
}

Then in your template, use a repeat.for on the answers property. Aurelia's binding system will ensure that there is an <answer> tag for each element in the answers array.

<!-- chatbox.html -->
<template>
 ...
<ul class="chat">
  <answer repeat.for="answer of answers" name.bind="answer.name" nickname.bind="answer.nickname"></answer>
</ul>
<button class="btn" click.trigger="addCustomElement()">Add</button>
... 
</template>


来源:https://stackoverflow.com/questions/31595103/how-do-get-aurelia-to-render-my-view-after-dynamically-adding-a-custom-element-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!