【问题标题】:Is there a callback or promise for Aurelia show.bind?Aurelia show.bind 是否有回调或承诺?
【发布时间】:2016-07-03 03:25:02
【问题描述】:

在我的模板中,我有一个 div 我想用作各种工具提示。选择模型后,工具提示会显示,然后我使用系绳将其放置在正确的位置。如果我在设置使元素显示的模型后立即设置系绳,则它的大小没有正确计算,并且系绳没有正确限制约束。如果我用 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);
}

谢谢!

【问题讨论】:

标签: javascript aurelia tether


【解决方案1】:

对 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 永远不会在代码中被调用,这是否意味着在编译代码时任务已经绑定,与微任务的绑定是否以另一种方式发生,或者您是否错过了?
  • 非常感谢!正是我想要的。
  • 在我的代码中,showTip 绑定到一个 SVG 路径,但它可以绑定到任何元素:mouseover.delegate="showTip($event, stateAlerts.get('KS'))"
猜你喜欢
  • 2014-09-27
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 2020-11-29
  • 2014-08-08
  • 2014-04-27
相关资源
最近更新 更多