2016-02-27 39 views
1

使用Aurelia,说我有一个自定义元素<panel>和视图/查看模型InfoPanel<panel>有一个关闭按钮,它应该对InfoPanel执行一些操作,例如,调用close()函数。如何访问Aurelia中的嵌套模型?

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

当我尝试,我得到了以下错误:

Uncaught Error: close is not a function
getFunction @ aurelia-binding.js:2033
evaluate @ aurelia-binding.js:1395
callSource @ aurelia-binding.js:4842
(anonymous function) @ aurelia-binding.js:4867
handleDelegatedEvent @ aurelia-binding.js:2972

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

+0

尝试 “裁判”,在这里看到:http://aurelia.io/docs.html#/aurelia/framework/1.0.0-beta.1.1.3/doc/article/cheat -sheet/5 –

+0

谢谢。我不太关注如何使用它来解决我的问题。你能举一个例子来回答吗? –

回答

6

你所要做的是可能的,但也有一些陷阱 -

Panel.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() { 
    } 
} 
+0

谢谢,使用'call'而不是'bind'修复了它。我还通过向VM添加自引用属性('this.vm = this')并在视图中将'close'函数绑定为像''所以'this'将被正确解析 - 非常混乱!您的解决方案效果很好,谢谢。 –