Another call function from custom element question


#1

The documentation for function call/bind in Aurelia is not great - some an end to end examples would have been helpful.

https://aurelia.io/docs/binding/basics#function-references

I am struggling to see how to call a function on my parent viewmodel from my custom element, passing arguments and maintaining the correct context - using .call as shown in the docs.

<template>
  <require from="./element"></require>
  <element callback.call="callback()"></element>
</template>
import {bindable} from 'aurelia-framework';
export class Sample {
  @bindable
  callback = val => {
    console.log('**********, val, this);
  };
}
<template>
  <button click.trigger="callback.call('mydata')">
    Click me</button>
</template>
import {bindable} from 'aurelia-framework';
export class Element {
  @bindable
  callback;
}

I’ve tried every permutation I can think of (including wrapping it in an object), but I cannot get the parameter mydata passed to the function using .call.

However, if I just use a simple .bind and call the callback function directly, it appears to work OK:

<template>
  <require from="./element"></require>
  <element callback.bind="callback"></element>
</template>
...
<template>
  <button click.trigger="callback('my data')">Click me</button>
</template>

If I can do that, what is the point of trying to use .call?


#2

You can try

<template>
  <require from="./element"></require>
  <element callback.call="callback($event)"></element>
</template>

#3

Thanks. That works. Still not exactly sure when I need to use .call - guessing I might need to do so if my callback function was a regular function:

callback() {}

rather than arrow function:

callback = () => {}

Why Aurelia Struggles to Gain Popularity
#4

Use call whenever you bind to a function of any kind.


#5

The advantage of .call is you can pass many args through the callback object in the element component but the parent can pick which ones it wants and they can be named whatever but it has to be contained in an object, in this case we want the data property not the click event.

<template>
  <require from="./element"></require>
  <element callback.call="someHandler(data)"></element>
</template>
import {bindable} from 'aurelia-framework';
export class Sample {
  @bindable
  someHandler = val => {
    console.log('**********', val, this);
  };
}
<template>
  <button click.trigger="callback({ event: $event, data: 'mydata' })">
    Click me
  </button>
</template>
import {bindable} from 'aurelia-framework';
export class Element {
  @bindable
  callback = () => {];
}