使用Aurelia动态添加到Dom [英] Dynamically add to Dom with Aurelia

查看:54
本文介绍了使用Aurelia动态添加到Dom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在查看 aurelia-dialog 项目(主要关注渲染器),因为我希望做类似的事情.我喜欢 toastr项目,但似乎无法使其与Aurelia CLI (尽管我可以使它与Typescript框架一起使用项目).我开始研究一个独立的解决方案(我希望它独立于jQuery而工作),但似乎无法理解为什么它不起作用.

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.

我使用au new命令创建了一个新项目. 我更新了app.ts文件以包含此文件:

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();
  }
}

,然后我在与app.ts文件相同的级别上添加了另一个文件toastr.ts.它的内容是这样的:

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);
        }
    }
}

如果我将代码放在showToast方法中,则代码可以正常运行并遇到断点,但是当我在浏览器中检查dom时,似乎根本没有将div添加到html中.

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.

我做错了什么?我如何才能将该元素实际插入到DOM中?我需要调用另一种方法来重绘html吗?我没有在aurelia-dialog项目中看到其他类似的东西.

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.

推荐答案

将调用移至Attached().

Move the call to attached().

我也是Aurelia的新手,似乎aurelia-pal DOM在初始渲染之前不起作用.

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();
  }
}

这篇关于使用Aurelia动态添加到Dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆