Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I reversely iterate on an aurelia array repeater?

I am trying to iterate from the end of an array to the beginning of it.

For example:

repeater-template.js:

export class RepeaterTemplate {
constructor() {
this.friends = [
  'Alice',
  'Bob',
  'Carol',
  'Dana'
  ];
 }
}

repeater-template.html:

 <template>
   <p repeat.for.reverse ="friend of friends">Hello, ${friend}!</p>
 </template>

output:

Hello Dana
Hello Carol
Hello Bob
Hello Alice
like image 693
Jafar Rasooli Avatar asked Jan 04 '23 19:01

Jafar Rasooli


2 Answers

I don't think the accepted solution will work if the array mutates. I believe the ideal is to create a value-converter that returns the reversed array without mutating the original one. For instance:

JS

export class App {
  message = 'Hello World!';

  friends = ['a', 'b', 'c'];

  attached() {
    //MUTATE!
    setTimeout(() => { this.friends.push('d') }, 300);
  }
}

export class ReverseValueConverter {
  toView(array) {
    return array.slice().reverse();
  }
}

HTML

<p repeat.for="friend of friends | reverse">Hello, ${friend}!</p>

Running example: https://gist.run/?id=20d00a205e651b6b4d7064e2f57d2675


We can't use a computed-property here because @computedFrom doesn't support collections yet https://github.com/aurelia/binding/issues/249.

Another possible solution is subscribing the array via BindingEngine and updating a reversed copy when it mutates, but that would be too much code to solve a simple problem.

Hope this helps!

like image 105
Fabio Luz Avatar answered Jan 06 '23 13:01

Fabio Luz


As far as I know Aurelia doesn't have any explicit functions for this, but you could make a simple function in the viewmodel:

reverse(arr) {
    return arr.slice().reverse();
}

Then in the view:

<template>
   <p repeat.for="friend of reverse(friends)">Hello, ${friend}!</p>
</template>
like image 26
Sitl Avatar answered Jan 06 '23 13:01

Sitl