Aurelia 自定义元素:访问父方法

2024-03-16

我正在使用 Aurelia 的自定义元素重复一组条目。这是示例要点:https://gist.run/?id=38aee85444712​​2f021bc05e1e0de25ae https://gist.run/?id=38aee854447122f021bc05e1e0de25ae

现在,我需要访问deleteEntry(entry)单击自定义元素中定义的按钮时的方法。我尝试使用$parent.deleteEntry(entry)但它不起作用。

Saw this https://stackoverflow.com/questions/32777303/custom-elements-binding-context-what-is-it-exactly-how-to-access-parent-vm问题,但它已经存在一年多了,我想知道现在是否有更干净的方法来实现这一目标。


为什么不使用call绑定来完成这个?

这是一个例子:https://gist.run?id=3cc553ea3bd7ed1862d87d8dbe4f5f84 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);
    }
}

条目.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在尝试调用它之前实际上是一个函数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Aurelia 自定义元素:访问父方法 的相关文章

随机推荐