Anj Anj - 1 year ago 358
Javascript Question

In Aurelia, can I bind a function from my containing view-model to be called by my custom element?

I have a custom element which will take user input, and on [save] button click, I want to pass information to the parent view-model so I can send it to the server and move to the next section. I'm going to simplify this for example's sake:


import { customElement, bindable } from 'aurelia-framework';

export class MyElement { }


<button click.delegate="save()">Click this</button>


export class ParentViewModel {
parentProperty = 7;
parentMethod() {
console.log(`parent property: ${this.parentProperty}`);


<require from="./my-element"></require>
<div class="content-panel">
<my-element save.bind="parentMethod"></my-element>

For a demo, see (app.js and app.html represent parent-view-model.js and parent-view-model.html):

It works! Kind of. Unfortunately,
seems to be bound to
instead of
, so in this example, what is printed to console is:
parent property: undefined
. That will not work.

I know I can utilize the EventAggregator to facilitate some communication between the custom element and the view-model, but if I can help it I'd like to avoid the added complexity.

Answer Source

You have two options for this. You could handle this using Custom Events, or you can do it using the call binding that Anj mentioned in his answer. Which one you use depends on your actual use case.

If you want the custom element to be able to call a method on your parent VM and pass data out of the custom element, then you should use a Custom Event as shown in this gist: You would basically attach any data you need to pass on the detail property of the Custom Event. In the event binding declaration, you would add $event as a parameter to the function and then check the detail property of $event in your event handler (you could also just pass $event.detail if you wanted).

If you want the custom element to be able to call a method on your parent VM and have data passed in from the parent VM (or from another custom element or something), then you should use the call binding. You can specify arguments that will be passed to the method by specifying them in the binding declaration ("myMethod(myProperty)". These arguments come from the VM context where the binding is being declared, not from the Custom Element's VM).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download