Search code examples
aurelia

Aurelia @bindable *Changed calls on initialisation


I'm finding that when I define a @bindable property, and a propertyChanged handler for it, it sometimes gets called before the custom component's bind() method and sometimes doesn't.

https://gist.run/?id=d7d9e7c7080f581f8e81b888268a2f11

In several places, I'm using these propertyChanged handler on one property to trigger updates to another, in situations where a @computedFrom isn't appropriate, as the second value is a complex calculation that I don't want called multiple times.

For now, I'm having to do the following:

@bindable propOne;
@bindable propTwo;

propOneChanged(newVal) {
  propTwo = "something complex " + newVal;
}

bind() {
**  propOneChanged(propOne);**
}

Is there any better way to do this (e.g. something in the @bindable decorator) so that I don't need to manually 'prime' the property in the bind()?


Solution

  • Is there any better way to do this (e.g. something in the @bindable decorator) so that I don't need to manually 'prime' the property in the bind()?

    No.

    If you don't have a bind() method, then Aurelia will call your change handlers during bind(). Unless you've got specific things you need to do (besides priming your bindables), remove the bind() method. Then you don't need to worry about this.

    If you do have a bind() method, then that's the correct place for you to invoke your change handlers.

    Also, I get the impression you're not entirely sure how bindables work.

    Simply put: a @bindable decorator tells the Aurelia framework to wrap that property in a get + set method (this happens when the component is loaded, way before its lifecycle).

    The set method invokes the change handler whenever it receives a value that's different from the current value - when you assign a value to a bindable, the change handler is invoked, regardless of whether the component is bound, even if it's not a ViewModel.

    So to address your comment:

    it sometimes gets called before the custom component's bind() method and sometimes doesn't.

    It will be called before the custom component's bind() method if and only if you assign some value to it before the custom component's bind(). For example, in the constructor or in the property initializer.