如何在Aurelia中访问嵌套模型

How to access nested model in Aurelia?

本文关键字:访问 嵌套 模型 Aurelia      更新时间:2023-09-26

使用 Aurelia,假设我有一个自定义元素<panel>和一个视图/视图模型InfoPanel<panel>里面有一个关闭按钮,它应该对InfoPanel执行一些操作,例如调用close()函数。

面板.html

<template>
    <h1>${headerText}</h1>
    <button click.delegate="close()">x</button>
    <content></content>
</template>

面板.js

@bindable({name: "headerText"})
@bindable({name: "close"})
export class Panel {
}

信息面板.html

<template>
    <require from="./Panel"></require>
    <panel header-text="Info" close.bind="close">
        <!-- content here -->
    </panel>
</template>

信息面板.js

export class InfoPanel {
    close() {
        // At this point, "this" referse to the Panel, not the InfoPanel instance.
    }
}

当我尝试这样做时,我收到以下错误:

未捕获错误:关闭不是一个函数
getFunction @ aurelia-binding.js:2033
评估@Aurelia-binding.js:1395
callSource @ aurelia-binding.js:4842
(匿名函数)@Aurelia-binding.js:4867
handleDelegatedEvent @ aurelia-binding.js:2972

我的假设是奥蕾莉亚不清楚上下文,或者我错过了一些东西......

你想做的事情是可能的,但有一些陷阱——

面板.html

<template>
    <h1>${headerText}</h1>
    <button click.delegate="close()">x</button>
    <content></content>
</template>

要获取面板.html绑定到关闭,我们需要默认使其成为匿名函数。 我正在使用 ES7 类实例字段(类属性的长名称),但您可以根据需要将装饰器用作类装饰器,前提是您正确设置了它 -

面板.js

export class Panel {
  @bindable headerText = '';
  @bindable close = () => {};
}

您需要使用 call 来传递函数引用,而不是尝试计算表达式的 bind -

信息面板.html

<template>
    <require from="./Panel"></require>
    <panel header-text="Info" close.call="close()">
        <!-- content here -->
    </panel>
</template>

信息面板.js

export class InfoPanel {
    close() {
    }
}