Reputation: 465
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()?
Upvotes: 4
Views: 1350
Reputation: 8047
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.
Upvotes: 3
Reputation: 1
the xyChanged protoype is xyChanged(newValue, oldValue)
. To prevent unwanted behaviour i'm always doing
if(oldvalue === null) return;
(which is null directly after bind()). If you use async model-requests its in most cases meaningfull to do a null check in your view
<div if.bind="model.data">...</div>
Upvotes: 0