【问题标题】:Execute function after content has been dynamically loaded in Aurelia在 Aurelia 中动态加载内容后执行函数
【发布时间】:2017-02-15 14:39:14
【问题描述】:

我正在使用Aurelia

我有一个post 路由,它会根据传递的id 显示一个帖子。 服务器编译用于将帖子写入 HTML 的 Markdown,我正在使用以下方法在模板中加载此内容:

<div innerHTML.bind="post.content"></div>

// in the activate() function
client
    .fetch(`api/post/${params.id}`)
    .then(res => res.json())
    .then(data => {
        this.post = data;

        // this is the workaround I am currently using
        setTimeout(this.displayLineNumbers, 200);
    });

当内容已附加到视图时,我找不到任何方法来执行函数。 如果我只使用:

this.post = data;
this.displayLineNumbers();

它将失败,因为内容尚未附加,因此我的功能要更改的元素尚不可用。我目前使用的解决方法是等待 200 毫秒,然后执行该函数。

有什么方法(事件或函数)可以知道何时附加了动态加载的内容?或者可能是 innerHTML.bind 之外的另一种内容模板方式?

【问题讨论】:

    标签: javascript aurelia aurelia-templating


    【解决方案1】:

    从技术上讲,Aurelia 已将自己附加到 DOM,并且对您在此阶段要放入页面中的内容一无所知。但是,这听起来像是任务队列的候选者。我还记得有一个您可以附加到主要针对 e2e 测试的事件,称为 aurelia-composed,但我从未需要或研究过它。

    任务队列允许您将任务推送到任务队列的底部,Aurelia 使用该任务队列来确定任务的优先级,例如 if/show 绑定等。我相信这可能会做你想做的事。

    import {TaskQueue} from 'aurelia-framework';
    
    activate() {
    client
        .fetch(`api/post/${params.id}`)
        .then(res => res.json())
        .then(data => {
            this.post = data;
    
            this.taskQueue.queueMicroTask(() => {
                this.displayLineNumbers();
            });
        });
    }
    

    【讨论】:

    • 这是一个很多人都问过的问题......也是一个很好的解决方案。似乎 Aurelia 应该考虑添加一个生命周期钩子(如果可能),它会自动添加 .queueMicroTask() 并调用 viewmodel 方法(如 bindingFinished())。
    • 我们建议为此使用queueMicroTask,并在我们的官方培训课程中教授。
    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2012-04-12
    • 2015-10-16
    相关资源
    最近更新 更多