Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia.js: How do I animate an element when bound value changes?

I am using Aurelia.js for my UI. Let's say I have the following view markup:

<tr repeat.for="item in items">
    <td>${item.name}</td>
    <td>${item.value}</td>
</tr>

Which is bound to a model "items". When one of the values in the model changes, I want to animate the cell where the changed value is displayed. How can I accomplish this?

like image 390
Mikhail Shilkov Avatar asked Jul 25 '15 20:07

Mikhail Shilkov


1 Answers

This can be done with Aurelia custom attributes feature.

Create a new javascript file to describe the attribute (I called the attribute "animateonchange"):

import {inject, customAttribute} from 'aurelia-framework';
import {CssAnimator} from 'aurelia-animator-css';

@customAttribute('animateonchange')
@inject(Element, CssAnimator)
export class AnimateOnChangeCustomAttribute {
    constructor(element, animator) {
        this.element = element;
        this.animator = animator;
        this.initialValueSet = false;
    }

    valueChanged(newValue){
        if (this.initialValueSet) {
            this.animator.addClass(this.element, 'background-animation').then(() => {
                this.animator.removeClass(this.element, 'background-animation');
            });
        }
        this.initialValueSet = true;
    }
}

It receives the element and CSS animator in constructor. When the value changes, it animates the element with a predefined CSS class name. The first change is ignored (no need to animate on initial load). Here is how to use this custom element:

<template>
    <require from="./animateonchange"></require>
    <div animateonchange.bind="someProperty">${someProperty}</div>
</template>

See the complete example in my blog or on plunkr

like image 71
Mikhail Shilkov Avatar answered Sep 27 '22 18:09

Mikhail Shilkov