Aurelia的show.bind有回调函数或Promise吗?

3
在我的模板中,我有一个 div,想将其用作工具提示。当我选择一个模型时,工具提示显示,然后我使用 tether 将其放置在正确的位置上。如果我在设置显示元素后立即设置 tether,那么它的大小不会被正确计算,而且 Tether 无法正确限制约束条件。如果我使用 setTimeout 进行防抖处理,就可以将其放在正确的位置上,但那感觉很假。我的问题是:
是否有一种回调机制可以附加到 show.bind 上,在使元素可见之后调用?
我的模板:
<div ref="tooltip" show.bind="selectedAlert" class="homepage-stats-tooltip panel panel-default">
    <div class="panel-body">
        <h1>${selectedAlert.Name}</h1>
        <dl>
            <dt>Normal</dt>
            <dd>${selectedAlert.NormalVolume}</dd>
            <dt>Current</dt>
            <dd>${selectedAlert.CurrentVolume}</dd>
        </dl>
    </div>
</div>

设置模型并调用 Tether 的函数:
showTip(event, state) {
    if (!state) {
        return;
    }

    console.log(`Show tip for ${state.Name}.`);
    this.selectedAlert = state;

    setTimeout(() => {
        new Tether({
            element: this.tooltip,
            target: event.target,
            attachment: "top left",
            targetAttachment: "top right",
            constraints: [
                {
                    to: this.usMap,
                    pin: true,
                    attachment: 'together'
                }
            ]
        });
    }, 10);
}

谢谢!


1个回答

4

DOM的更改,如由对selectedAlert属性的更改引发的show,会被排入aurelia的微任务队列中。这样可以批处理DOM更改,有利于性能。您可以将自己的任务排入微任务队列中,它们将在元素变为可见后执行:

import {TaskQueue} from 'aurelia-task-queue';

@inject(TaskQueue)
export class MyComponent {
  constructor(taskQueue) {
    this.taskQueue = taskQueue;
  }

  showTip(event, state) {
    if (!state) {
        return;
    }

    console.log(`Show tip for ${state.Name}.`);
    this.selectedAlert = state; // <-- task is queued to notify subscribers (eg the "show" binding command) that selectedAlert changed

    // queue another task, which will execute after the task queued above ^^^
    this.taskQueue.queueMicroTask(() => {
        new Tether({
            element: this.tooltip,
            target: event.target,
            attachment: "top left",
            targetAttachment: "top right",
            constraints: [
                {
                    to: this.usMap,
                    pin: true,
                    attachment: 'together'
                }
            ]
        });
    });
  }

}

只是关于你的回答的一个问题:在代码中从未调用showTip,这是否意味着任务在编译代码时已经绑定,绑定到微任务的方式是另一种方式,还是你忽略了这一点? - Randy
非常感谢!正是我所寻找的。 - Jereme
在我的代码中,showTip绑定到了一个SVG路径,但它也可以绑定到任何元素上:mouseover.delegate="showTip($event, stateAlerts.get('KS'))"。 - Jereme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接