unsalted
unsalted

Reputation: 353

Aurelia - event load / "lazy load" images

I'm very new to Aurelia, but I am enjoying it so far. I want to make sure that I'm doing this the "Aurelia" way - and I'm not missing something because my new-platform-spidey-senses™ are telling me that I'm doing something wrong.

For now i'm simply trying to change the class of an image onLoad for "animations, pretty loading, and such"...(clients)

My approach thus far:

template

<template>
  <div class="random" repeat.for="thumb of thumbs">
    <img 
        alt="thumb.name" 
        src.bind-one-time="${server}/${thumb.uri}"
        load.trigger="loaded(thumb)"
        class.bind="thumb.loaded"
        class="lazyload"
     />
  </div>
</template>

view-model

import { HttpClient } from 'aurelia-fetch-client'
import environment from './environment'

export class App {

  constructor() {
    this.client = new HttpClient()
    this.thumbs = []
    this.loaded = t => { t.loaded = 'loaded' }
  }

  activate() {
    return this.client.fetch(`${environment.api}/api`)
      .then(response => response.json())
      .then(data => {
        this.data = data
        this.thumbs = data.map(item => {
          if (item.thumbnails)
            return item.thumnails
        )}
      )}
    }
  }

This is abridged code -- trying to keep things legible. Nearest I can tell event.trigger (as apposed to event.delegate) is necessary in this instance, and using the already bound thumb data is probably my best bet.

Thoughts...?

Upvotes: 2

Views: 1214

Answers (1)

Jeremy Danyow
Jeremy Danyow

Reputation: 26406

What you have looks pretty good to me. Here's a few tweaks you could try that might streamline the code a bit:

https://gist.run?id=251638547841a34746d9cbd874da14e2

app.html

<template>
  <div repeat.for="thumb of thumbs">
    <img 
      alt.one-time="thumb.name" 
      src.one-time="server + '/' + thumb.uri"
      load.trigger="$event.target.classList.add('loaded') & oneTime"
      class="thumbnail"
     />
  </div>
</template>

app.js

export class App {
  server = 'https://i.imgur.com';
  thumbs = [
    { name: 'SpaceX', uri: 'xSraADG.jpg' },
    { name: 'SpaceX', uri: 'HSeX7Nn.jpg' },
  ];
}

Upvotes: 2

Related Questions