11

I have one custom element named custom-element and I put it inside template A (with controller A)

custom-element

export class CustomElem {
  @bindable onCompleted;
  ........
}

And updateDescription() is one function of controller A.

export class A {
  updateDescription(){
    ....
  }
}

How to call updateDescription() by using custom-element?

Jeremy Danyow
  • 26,470
  • 12
  • 87
  • 133
Chu Văn Nam
  • 121
  • 2
  • 5

2 Answers2

22

Use the call binding command to give a reference to a function call to your custom element:

<custom-element on-completed.call="updateDescription()"></custom-element>

To call the updateDescription method with arguments, you can do the following:

export class CustomElem {
  @bindable onCompleted;

  ...

  fooBarBaz() {
    var args = {
      something: 'A',
      somethingElse: 'B',
      anotherArg: 'C'
    };
    this.onCompleted(args);
  }
}
<custom-element on-completed.call="updateDescription(something, somethingElse, anotherArg)"></custom-element>
Jeremy Danyow
  • 26,470
  • 12
  • 87
  • 133
2
export class A {
  updateDescription = () => {
  };
}

Then

<custom-element on-completed.bind="updateDescription"></custom-element>

inside CustomElem call this.onCompleted()

valichek
  • 1,186
  • 6
  • 9
  • Just tried this, and unfortunately, while it works well, the execution context remains with the custom control, meaning that NONE of the properties in the parent VM are accessible. This is a good way to do things if you want to extend the code inside the custom control, but allow the consumer to define the code that does so inside their own VM on a control by control basis. – shawty Jun 06 '17 at 16:12
  • @shawty if you need some outer context inside updateDescription it is always possible to create a closure. Sometimes it could be a good solution – valichek Jun 06 '17 at 17:16