我正在构建一个拖放式工作区,类似于您找到的用于制作模型的工作区。我有一个工作区自定义元素,它有一个更大的嵌套元素,可以缩放和平移。因此,我需要仔细跟踪工作区和所有包含元素的大小和位置数据。
在自定义元素的附加事件中,我以编程方式将工作区的高度和宽度设置为 JavaScript 对象,该对象绑定(bind)到 View 中的 css:
workspaceCustomElement.js
export class WorkspaceCustomElement {
constructor(element) {
this.element = element;
}
attached() {
this.workspace.size = {
height: this.element.height * 5,
width: this.element.width * 5
}
}
}
workspaceCustomElement.html
<div css="height: ${workspace.height}px; width: ${workspace.width}px;
left: ${(element.clientWidth - workspace.width)/2}px;
top: ${(element.clientHeight - workspace.height)/2}px;"></div>
现在我在尝试获取子元素的位置时遇到了问题。我也在它们上附加了回调,但是它们在上面附加的回调之前被评估,所以 css 绑定(bind)没有被评估,并且大小和位置是错误的。
我需要在attached()
被评估并且绑定(bind)被更新后添加一个回调。我可以通过使用 setTimeout
hack,但我不相信这会一直有效。
attached() {
this.workspace.size = {
height: this.element.height * 5,
width: this.element.width * 5
}
setTimeout(() => {
let components = this.element.querySelectorAll('.component');
Array.prototype.forEach.call(components, (component) => {
let model = component.model;
model.position = {
x: component.clientLeft,
y: component.clientTop
};
}
}, 0)
}
是否有更好、更可靠的方法在下一次绑定(bind)更新后对指令进行排队?
最佳答案
最佳实践是将任务添加到 TaskQueue
。在幕后,绑定(bind)引擎使用 TaskQueue
本身,因此添加新任务会将其排入绑定(bind)更新之后。
workspaceCustomElement.js
export class WorkspaceCustomElement {
constructor(element, queue) {
this.element = element;
this.queue = queue;
}
attached() {
this.workspace.size = {
height: this.element.height * 5,
width: this.element.width * 5
}
this.queue.queueMicroTask(() => {
let components = this.element.querySelectorAll('.component');
Array.prototype.forEach.call(components, (component) => {
let model = component.model;
model.position = {
x: component.clientLeft,
y: component.clientTop
};
}
});
}
}
查看此处了解更多信息:TaskQueue API
关于javascript - 在 Aurelia 中重新评估绑定(bind)后触发回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385143/