在组件外部调用组件功能

时间:2016-01-28 04:50:03

标签: aurelia

在Aurelia中,我说有一个名为popup的自定义组件,其上有openclose方法。我可以在组件中调用这些方法,但是如何从组件外部调用它们呢?

app.html:

<template>
  <require from="popup"></require>

  Pop-up test
  <popup>
    <popup-body>
      <button click.trigger="close()">Close</button>
    </popup-body>
  </popup>
</template>

popup.html:

<template>
  <button click.trigger="open()">Open</button>
  <button click.trigger="close()">Close</button>

  <div class="popup" show.bind="visible">
    Pop-up!
    <content select="popup-body"></content>
  </div>
</template>

popup.js

export class Popup {
  constructor() {
    this.visible = false;
  }

  open() {
    this.visible = true;
  }

  close() {
    this.visible = false;
  }
}

注意在app.html中我添加了一个按钮来尝试关闭模式。显然close()将不起作用,因为它正在app.js中寻找该方法。如何在popup.js中调用close方法?

以上是working Plunker example

2 个答案:

答案 0 :(得分:3)

您可以使用view-model.ref

来获取组件的视图模型
<popup view-model.ref="popup">

然后致电关闭:

export class App {
  close(){
    popup.close();
  }
}

here is the plunker

答案 1 :(得分:1)

哦,我想我用view-model.ref

来解决这个问题
<template>
  <require from="popup"></require>

  Pop-up test
  <popup view-model.ref="popup">
    <popup-body>
      <button click.trigger="popup.close()">Close</button>
    </popup-body>
  </popup>
</template>