Aurelia Custom Elements: Access Parent method

跟風遠走 提交于 2019-12-23 07:05:41

问题


I am using Aurelia's Custom Elements to repeat over a set of entries. Here is the sample gist: https://gist.run/?id=38aee854447122f021bc05e1e0de25ae

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.


回答1:


Why not use the call binding to accomplish this?

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();
    }

}

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.




回答2:


Using bind life cycle event you can get parent View modal in Aurelia.

bind(bindingContext, overrideContext) {
        this.parent = bindingContext;
    }

Now you can access all the variables and methods from parent view to your view.

Like below code in child view

this.parent.parentmethod();


来源:https://stackoverflow.com/questions/41390793/aurelia-custom-elements-access-parent-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!