问题描述
我正在使用Aurelia的自定义元素"在一组条目上重复.以下是示例要点: https://gist.run/?id=38aee854447122f021bc05e1e0de25ae
I am using Aurelia's Custom Elements to repeat over a set of entries. Here is the sample gist: https://gist.run/?id=38aee854447122f021bc05e1e0de25ae
现在,单击自定义元素中定义的按钮时,我需要访问deleteEntry(entry)
方法.我尝试使用$parent.deleteEntry(entry)
,但无法正常工作.
Now, I need to access the deleteEntry(entry)
method when clicked on the button defined in custom element. I tried using $parent.deleteEntry(entry)
but it's not working.
看到此问题,但是它已经使用了一年多了,我想知道现在是否有一种更清洁的方法来实现这一目标.
Saw this issue, but it's more than an year old and I am wondering if there is a cleaner way to achieve this now.
推荐答案
为什么不使用call
绑定来完成此任务?
Why not use the call
binding to accomplish this?
以下是一个示例: https://gist.run?id=3cc553ea3bd7ed1862d87d8dbe4f5f84 strong>
Here's an example: https://gist.run?id=3cc553ea3bd7ed1862d87d8dbe4f5f84
app.html
<template>
<require from="./entry"></require>
<h2 class='text-center'>Journal Entries</h2>
<div>
<entry repeat.for='entry of entries' entry.bind='entry' delete-function.call="deleteEntry(entry)"></entry>
</div>
</template>
app.js
export class App {
entries = [{
'date': 'Jan 1',
'note': 'Hello World'
}, {
'date': 'Jan 2',
'note': 'Good Morning'
}];
deleteEntry(entry) {
console.log("Deleting entry");
console.log(entry);
const index = this.entries.indexOf(entry);
this.entries.splice(index, 1);
}
}
entry.html
<template>
<div>${entry.date} <button click.trigger='delete()'>X</button></div>
<div>${entry.note}</div>
</template>
entry.js
import {bindable} from 'aurelia-framework';
export class EntryCustomElement {
@bindable entry;
@bindable deleteFunction;
delete() {
this.deleteFunction();
}
}
很明显,在一个实际的实现中,您需要确保绑定到deleteFunction
的实际上是一个函数,然后再尝试调用它.
Obviously in a real implementation, you'll need to make sure that what is bound to deleteFunction
is actually a function before trying to call it.
这篇关于Aurelia自定义元素:访问父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!