[英]How to access nested model in Aurelia?
Using Aurelia, say I have a custom element <panel>
and a view/view-model InfoPanel
. 使用Aurelia,说我有一个自定义元素
<panel>
和一个view / view-model InfoPanel
。 <panel>
has a close button in it, which should perform some action on InfoPanel
, eg call the close()
function. <panel>
有一个关闭按钮,该按钮应在InfoPanel
上执行某些操作,例如,调用close()
函数。
Panel.html Panel.html
<template>
<h1>${headerText}</h1>
<button click.delegate="close()">x</button>
<content></content>
</template>
Panel.js Panel.js
@bindable({name: "headerText"})
@bindable({name: "close"})
export class Panel {
}
InfoPanel.html InfoPanel.html
<template>
<require from="./Panel"></require>
<panel header-text="Info" close.bind="close">
<!-- content here -->
</panel>
</template>
InfoPanel.js InfoPanel.js
export class InfoPanel {
close() {
// At this point, "this" referse to the Panel, not the InfoPanel instance.
}
}
When I try this, I get the following error: 尝试此操作时,出现以下错误:
Uncaught Error: close is not a function
未捕获的错误:close不是函数
getFunction @ aurelia-binding.js:2033getFunction @ aurelia-binding.js:2033
evaluate @ aurelia-binding.js:1395评估@ aurelia-binding.js:1395
callSource @ aurelia-binding.js:4842callSource @ aurelia-binding.js:4842
(anonymous function) @ aurelia-binding.js:4867(匿名函数)@ aurelia-binding.js:4867
handleDelegatedEvent @ aurelia-binding.js:2972handleDelegatedEvent @ aurelia-binding.js:2972
My assumption is that the context is unclear to Aurelia, or I'm missing something... 我的假设是Aurelia不清楚上下文,或者我缺少了某些东西...
What you are trying to do is possible but there are a few gotchas - 您尝试做的事是可能的,但是有一些陷阱-
Panel.html Panel.html
<template>
<h1>${headerText}</h1>
<button click.delegate="close()">x</button>
<content></content>
</template>
To get panel.html to bind to close we need to make it an anonymous function by default. 要使panel.html绑定关闭,我们需要默认将其设为匿名函数。 I am using ES7 class instance fields (a long name for class properties) but you can use the decorator as a class decorator as you are, provided you set it up correctly -
我正在使用ES7类实例字段(类属性的简称),但只要设置正确,就可以按原样使用装饰器作为类装饰器-
Panel.js Panel.js
export class Panel {
@bindable headerText = '';
@bindable close = () => {};
}
You need to use call
to pass a function reference instead of bind
which tries to evaluate the expression - 您需要使用
call
来传递一个函数引用,而不是bind
它试图计算表达式-
InfoPanel.html InfoPanel.html
<template>
<require from="./Panel"></require>
<panel header-text="Info" close.call="close()">
<!-- content here -->
</panel>
</template>
InfoPanel.js InfoPanel.js
export class InfoPanel {
close() {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.