How to use Aurelia binding decorator on a property with getter and setter

I have no problem using a decorator @bindablefor a class property. For instance.

export class SomeClass {
    @bindable public SomeProperty: Date = new Date();
}

But I'm at a dead end when it comes to using it with properties that have a getter / setter implementation. For instance.

export class SomeClass2 {
    // Where should the @bindable go now?
    private _someProperty: Date = new Date();

    public get SomeProperty(): Date {
        return this._someProperty;
    }

    public set SomeProperty(value: Date) {
        // Do some manipulation / validation here
        this._someProperty = value;
    }
}

I am sure I am missing something simple here ...

+4
source share
1 answer

The interacting one works by adding a getter and setter to its resource, which it uses to observe the changes. He recommended using a callback method ${propertyName}Changed(newValue, oldValue)to accomplish what you are trying to do. Here is an example of ES2016:

ViewModel

import {bindable} from 'aurelia-framework';

export class MyCustomElement {
  @bindable name;

  _name;
  errorMessage = '';

  nameChanged(newValue) {
    if(newValue.length >= 5 ) {
      this.errorMessage = 'Name is too long';
    }
    else {
      this._name = newValue;
      this.errorMessage = '';
    }
  }
}

View

<template>
  <p>Name is: ${_name}</p>
  <p>Error is: ${errorMessage}</p>
</template>

, ES2016 , . , TypeScript, , , name nameChanged. , newValue this._name .

+8

All Articles