efunneko
efunneko

Reputation: 511

In Aurelia, what is the correct way to add temporary and dynamic elements

I want to achieve an effect that I can have a view-model trigger the creation of one or more temporary elements in the DOM. These elements would be deleted after some period of time.

See this fiddle for a simple example of the effect I am after.

Here is a simple jQuery way of doing it:

var count = 1;
$("button").bind("click", function(e) {
    createNewNotifier(count++);
});

function createNewNotifier(text) {
    var div = $('<div></div>').appendTo(".notifications");
    div.text("Notification: " + text);
    div.hide(4000, function(){ $target.remove(); });
}

Upvotes: 1

Views: 174

Answers (1)

PW Kad
PW Kad

Reputation: 14995

You can just have an array of notifications that you publish notifications to -

export class Notifier {
  notifications = [];
  addNotification(notification) {
    this.notifications.push(notification);
    setTimeout(() => { 
      let index = this.notifications.indexOf(notification);
      notifications.splice(index, 1);
  }
}

in some view -

<template>
  <ul>
    <li repeat.for="notification of notifier.notifications">${notification.value}</li>
  </ul>
</template>

and in your view-model

   import {Notifier} from './notifier';
   export class ViewModel {
     static inject = [Notifier];
     constructor(notifier) {
       this.notifier = notifier;
     }
     attached() {
       this.notifier.add({ value: 'Attached!' });
     }
   }

Upvotes: 2

Related Questions