Dynamically add to Dom with Aurelia

一笑奈何 提交于 2019-12-24 08:47:00

问题


I've been looking at the aurelia-dialog project(focused mostly on the renderer piece) as I was hoping to do something similar. I like the toastr project, but can't seem to get it to work with Aurelia CLI(though I can get it to work with the Typescript skeleton project). I started to work on an independent solution(I would like it to work independent from jQuery), but can't seem to understand why this isn't working.

I created a new project using the au new command. I updated the app.ts file to contain this:

import {Toastr} from './toastr';

export class App {
  constructor() {
    new Toastr().showToast();
  }
}

and I added one other file toastr.ts at the same level as the app.ts file. It's contents are this:

import {DOM} from 'aurelia-pal';

export class Toastr {
    showToast() {
        let body = DOM.querySelectorAll('body')[0];
        let toastrContainer = DOM.getElementById('toastr-container');

        if(!toastrContainer) {
            toastrContainer = DOM.createElement('div');
            toastrContainer.id = 'toastr-container';
            toastrContainer.textContent = 'boo';
            body.insertBefore(toastrContainer, body.firstChild);
        }
    }
}

The code runs fine and hits a breakpoint if I place it inside the showToast method, but when I inspect the dom in the browser, it doesn't seem to add the div to the html at all.

What am I doing wrong? How can I get this element to actually be inserted into the DOM? Is there another method I need to invoke for the html to be redrawn? I didn't see anything else like that in the aurelia-dialog project.


回答1:


Move the call to attached().

I am new to Aurelia too, it seems like aurelia-pal DOM doesn't work before initial rendering.

import {Toastr} from './toastr';

export class App {
  attached() {
    new Toastr().showToast();
  }
}


来源:https://stackoverflow.com/questions/39106478/dynamically-add-to-dom-with-aurelia

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