mardi 7 avril 2020

Calculating image natural width on initial page load with ember-render-modifiers in Ember Glimmer components

Prior to using Ember's new Glimmer components, I used the didInsertElement lifecycle hook to calculate the natural width of an image element. I am passing in a target width so I can resize the image in the browser.

didInsertElement() {
    this._super(...arguments);
    if (this.targetWidth && this.targetWidth < this.element.naturalWidth) {
        this.targetHeight = Math.round(this.targetWidth / this.element.naturalWidth * this.element.naturalHeight);
        set(this, 'width', this.targetWidth);
        set(this, 'height', this.targetHeight);
    }
    else {
        set(this, 'width', this.naturalWidth);
        set(this, 'height', this.naturalHeight);
    }

With Glimmer components, and using @ember/render-modifiers, the src being passed in by the parent:

<img  src= width= height=>

In the component JS file

@action
calculateDimensions(element) {
    if (this.args.targetWidth && this.args.targetWidth < element.naturalWidth) {
        this.height = Math.round(this.args.targetWidth / element.naturalWidth * element.naturalHeight);
        this.width = this.args.targetWidth;
    }
    else {
        this.width = element.naturalWidth;
        this.height = element.naturalHeight;
    }
    element.setAttribute("width", this.width);
    element.setAttribute("height", this.height);
}

This all works fine if you reload the index/home page. However, when you first arrive at the site, the image is not rendered, because the value for element.naturalWidth is zero. The element is present, and if it's logged to the console I can see the values for natural width and height. Is the ember-render-modifier not a full replacement for didInsertElement?

Any help much appreciated.




Aucun commentaire:

Enregistrer un commentaire