Aurelia custom elements: parent method access

I use Aurelia custom elements to repeat over a set of records. Here is a gist example: https://gist.run/?id=38aee854447122f021bc05e1e0de25ae

Now I need to access the deleteEntry(entry) method when I click the button specified in the user element. I tried using $parent.deleteEntry(entry) , but it does not work.

I drank this question, but it is more than a year, and I wonder if there is a cleaner way to achieve this now.

+6
source share
2 answers

Why not use a call binding to accomplish this?

Here is 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 need to make sure that binding to deleteFunction is actually a function before trying to call it.

+9
source

Using the binding lifecycle event, you can get the parent view. View in Aurelia.

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

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

As below code in child view

 this.parent.parentmethod(); 
+1
source

Source: https://habr.com/ru/post/1013625/


All Articles