Using the @bindable attribute on child class in Au

2019-08-10 12:17发布

问题:

For the current project at work, we are creating quite a few custom controls that all share the same properties and that are bindable.

@bindable required: boolean = false;
@bindable minLength: number = 0;
@bindable maxLength: number = 0;

Since we'd like to avoid code duplication, the idea is to keep these bindable properties in a separate class, called 'Validation' in this case.

import {Validation} from "./validation";

export class MyClass {
  private validation: Validation = new Validation();

  // also tried:
  // @bindable validation: Validation = new Validation();
}

The question is how to get the HTML to bind to the properties in the Validation class. Doing this validation.required.bind="someProperty.required" doesn't update the required property on the validation instance. We attempted to use DI, but that didn't seem to cut it either.

import {inject} from "aurelia-framework";
import {Validation} from "./validation";

@inject(Validation)
export class MyClass {
  constructor(private validation: Validation) {
    this.validation = validation;
  }
}

Any hints would be greatly appreciated.

EDIT:

It seems that Aurelia interprets 'validation.required' as a command rather than an expression.

WARN [templating-binding] Unknown binding command. Object {defaultBindingMode: null, attrName: "validation", attrValue: "true", command: "required", expression: null}

回答1:

As a work-around until inheritance with bindable properties gets supported in Aurelia, I am binding to a class that has some of the shared properties. The bindable ones will get duplicated across the controls for now.

import {bindable, bindingMode} from "aurelia-framework";
import {IControlBase, ControlBase} from "./controlbase";

export class MyClass {
  @bindable controlbase: IControlBase = new ControlBase();
  @bindable label: string = "";
  @bindable editing: boolean = false;
  @bindable({ defaultBindingMode: bindingMode.twoWay })
  value: string;
}