asemahle
asemahle

Reputation: 20805

Aurelia - Custom element property binding resolution

I have created a custom element with an @bindable property. In the element's constructor another property is set using the value of the bound property. This is the code for the custom element (file name custom-element.ts):

import {bindable} from 'aurelia-framework';

export class CustomElement{

  @bindable value: any = null;
  message: any;

  constructor(){
    this.message = this.generateMessage();
  }

  generateMessage(){
    if (this.value != null){
      // logic to generate and return message
    } else {
      return "Someting went wrong";
    }
  }
}

This model has a the simple related view (file name custom-element.html):

<template>
  The value id is: ${value.id}, and the message is: ${message}
</template>

I use this element in a view elsewhere, whose model has access to the value object:

<require from="resources/custom-element"></require>
<custom-element value.bind="value"></custom-element>

While ${value.id} displays correctly, the ${message} is always Something went wrong.

When is value being set, and how can I use its value to set message?

Upvotes: 1

Views: 336

Answers (1)

nemesv
nemesv

Reputation: 139758

The constructor is called when your custom element is initally created however the data-binding will happen later in its lifecycle.

In order to get access to the bound properties you need to use the bind lifecycle callback (or attached depending on your actual needs) to set your message:

export class CustomElement{

  @bindable value: any = null;
  message: any;

  bind() {
    this.message = this.generateMessage();
  }

  generateMessage(){
    if (this.value != null){
      // logic to generate and return message
    } else {
      return "Someting went wrong";
    }
  }
}

As an alternative solution you can subscribe on your value property changed event with implementing a method with the naming convention: yourPropertyChanged (so in your case valueChanged) and do the message generation there:

valueChanged(newValue) {
  this.message = this.generateMessage(newValue);
}

generateMessage(newValue){
  if (newValue != null){
    // logic to generate and return message
  } else {
    return "Someting went wrong";
  }
}

Upvotes: 2

Related Questions