Example of Binding Inheritance

This was in the October release notes, does anyone have a simple example of how it can be used?

Inheritance of Bindables - Now you can inherit custom elements to inherit the bindable properties! This addresses the most common request for basic component inheritance scenarios.

I have come custom elements which have some bindable properties that are the same but the templates aren’t.

1 Like

You’ll found more info here:

A simple example along your description is this:

class BaseBehavior {
  @bindable frob = 4;
  @bindable bar = 2;
}

@customElement
@useView(PLATFORM.moduleName('./some-view.html'))
export class OneCustomElement extends BaseBehavior {
}

@customElement
@useView(PLATFORM.moduleName('./another-view.html'))
export class AnotherCustomElement extends BaseBehavior {
}
3 Likes

Here is another example of using inheritance with Aurelia bindable:

class hierarchy:

  • FieldBehavior
    • TriggerField
      • NumberField
      • SelectField

The SelectField also has an override-able class method to provide template for the list, so you can override it right there, or in its sub classes

1 Like

I assume that the constructor still needs to be handled by the subclass, like below. How about abstract superclasses, also below?

export abstract class ClassA {

  @bindable amount: number;

  constructor(protected additionService: AdditionService) {
  }

  get doubleAmount(): number {
      return this.additionService.add(this.amount, this.amount);
  }

}


@inject(AdditionService, MultiplyService)
@customElement("triple-amount") // Is this valid for webpack, or does PLATFORM.moduleName('./triple-amount) need to be used?
export class ClassB extends ClassA {

  // additionService not marked private or protected
  constructor(additionService: AdditionService, 
              private multiplyService: MultiplyService) { 
    super(additionService);
  }

  get tripleAmount(): number {
      return this.multiplyService.multiply(this.amount, 3);
  }

}

The documentation is a little light, or just not clear enough.

1 Like

yes you will need to call the base constructor with any arguments it expects - its not an aurelia concept, this is typescript/es6 syntax. see super - JavaScript | MDN (mozilla.org).

2 Likes

Sounds good. That’s what I assumed. I just wanted sure if not implementing a constructor would inherit from the parent.

1 Like

Note that:

  • unlike other languages, subclasses of abstract classes do not need to re-implement inherited constructors if the arguments are unchanged
  • @autoinject works on abstract classes

This can prevent a high amount of repeated code and works fine with inherited @bindables.

2 Likes