Hi there!
I’m new to aurelia, so this might be a bit basic, but I need to calculate the sizes of an element that’s “currently” hidden using a show.binding. I use the ref-keyword to access it in the view model, and when it’s hidden, all the sizes are 0. I suppose it’s quite ugly to save these values before hiding the element in a separate variable in the view model. Is there any nice, pretty, simple way of getting this data?
Suppose your element with show.bind
is bounded to a property name isVisible
:
import { observable } from 'aurelia-framework';
class ABC {
// populated by Aurelia ref binding
readonly element: HTMLElement;
// this is the cache for element size before it gets display: none
elementRectSnapshot: ClientRect;
@observable()
isVisible: boolean;
isVisibleChanged(newValue: boolean) {
// element reference will only be available after bind lifecycle
// so we do nothing when element is not available
if (!this.element) {
return;
}
// If new value is falsy,
// the element it's bound with will be hidden
if (!newValue) {
this.elementRectSnapShot = this.element.getBoundingClientRect();
}
}
}
Why it works: changeHandler
of @observable
is called synchronously, thus will be executed before bindings. Which means isVisibleChanged
will be executed before the element gets hidden, so the size should be valid. For more on difference between @observable
and @bindable
, you can have a look at Difference between @observable and @bindable
1 Like
Thank you! That seems promising, I will give it a go!