Aurelia - call function on a nested component

I want to call a child component from a parent. I have a way to do this, but I want to know if there is not a better way.

From Ashley Grant 's blog post about accessing a custom viewModel from a custom attribute, I see that Aurelia adds auto the element and you can access the viewModel through this. So, if I add a nested component with ref, like this:

<template>
    <nested-element ref="childElement"></nested-element>
</template>

I can call the function on it as follows:

this.childElement.au.controller.viewModel.someFunction();

That's cool. I was hoping that I would be able to access the nested viewModel using the parameters to the hook that implements the parent, for example created(owningView, myView), but I cannot find the path to it.

Did I miss the best way?

: , , , view

+4
2

ref . view-model.ref .

<template>
    <nested-element view-model.ref="childViewModel"></nested-element>
</template>

, -:

this.childViewModel.someFunction();
+7

, . Javascript :

bar.html

<template>
  <h1>${value}</h1>
    <input type="text" value.bind="value"></input>
    <foo>text</foo>
</template>

bar.ts

import {bindable} from 'aurelia-framework';
export class Bar {

  @bindable value;

  public valueChanged(newValue, oldValue) {
    var event = new CustomEvent("some-event-name", { "detail": { message: "Hello from Bar", oldValue, newValue } });
    document.dispatchEvent(event);
  }
}

foo.html

<template>
  <h1>${value}</h1>
</template>

foo.ts

import {bindable} from 'aurelia-framework';

export class Foo {
  constructor() {
    document.addEventListener("some-event-name", (e) => {
      console.log('hello here is Foo, recieved event from Bar : ', e);
    }, true);
  }
}
+1

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


All Articles