【问题标题】:How to access nested model in Aurelia?如何访问 Aurelia 中的嵌套模型?
【发布时间】:2016-02-28 06:26:18
【问题描述】:

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

Panel.html

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

Panel.js

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

InfoPanel.html

<template>
    <require from="./Panel"></require>

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

InfoPanel.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

我的假设是 Aurelia 不清楚上下文,或者我遗漏了一些东西......

【问题讨论】:

标签: javascript aurelia


【解决方案1】:

您尝试做的事情是可能的,但有一些问题 -

面板.html

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

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

Panel.js

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

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

InfoPanel.html

<template>
    <require from="./Panel"></require>

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

InfoPanel.js

export class InfoPanel {
    close() {
    }
}

【讨论】:

  • 谢谢,使用call 代替bind 修复了它。我还通过向我的 VM (this.vm = this) 添加一个自引用属性并在视图中绑定 close 函数来修复它,如 &lt;panel ... close.bind="close.bind(vm)"&gt; 这样this 将被正确解析 - 非常混乱!您的解决方案效果很好,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
相关资源
最近更新 更多