Есть ли способ указать имя столбца в пользовательской функции сортировки таблицы Aurelia? - PullRequest
0 голосов
/ 07 мая 2018

Это может быть очень специфический способ использования таблицы aurelia, но я хотел бы знать, есть ли какой-либо способ доступа к ключу, который вы определяете в параметрах aut-sort в функции custom.bind.

Вместо заполнения таблицы с использованием статического массива для data я загружаю в массив JSON и динамически создаю таблицу на основе содержимого JSON, поэтому я не могу использовать aut-sort, указывая на массив список значений.

Если бы я мог получить доступ только к значению ключа, основанному на столбце, который я щелкаю, чтобы отсортировать, то я смог бы использовать пользовательскую сортировку для своих нужд.

Я уже пытался определить глобальную строку и прикрепить обновление к этой строке, используя change.delegate в заголовках таблицы Aurelia, но change.delegate запускает после сортировки custom.bind и * В любом случае функция 1016 * распространяется только на таблицу Aurelia.

<table aurelia-table="data.bind: data; display-data.bind: $resultsData; current-page.bind: currentPage; page-size.bind: pageSize; total-items.bind: totalItems; api.bind: tableApi;">
            <thead>
                <tr>
                    <th repeat.for="[k,v] of responseFields" aut-sort="custom.bind: someSort">${v.displayName}</th>
                </tr>
            </thead>
            <tbody>
                <tr repeat.for="result of $resultsData">
                    <td repeat.for="[k,v] of responseFields">
                        ${result[k]}
                    </td>
                </tr>
            </tbody>
        </table>

Map просто позволяет мне динамически устанавливать заголовки.

А вот и функция сортировки:

someSort(a, b, sortOrder) {
    let sortColumnName = this.sortColumnName;
    let code1 = this.data[this.data.indexOf(a)][sortColumnName];
    let code2 = this.data[this.data.indexOf(b)][sortColumnName];

    if (code1 === code2) {
        return 0;
    }
    if (code1 > code2) {
        return 1 * sortOrder;
    }
    return -1 * sortOrder;
}

Я хотел бы иметь возможность определить sortColumnName, но в настоящее время я не могу, если я не кодирую его жестко, но мне нужно, чтобы он был динамическим.

Ответы [ 2 ]

0 голосов
/ 30 октября 2018

Я смог заставить это работать с помощью click.capture, который вызывает функцию с индексом (click.delegate не работал, так как он был запущен после custom.bind) заголовка.

<tr class="table-header">
<th repeat.for="item of tableData.columns" click.capture="sort($index)" aut-sort="custom.bind: sortList">
   ${item}
   <div class="arrow"></div>
</th>

sort () просто устанавливает приватную переменную

private sortIndex = 0;
public sort(index) {
this.sortIndex = index;
}

и моя пользовательская сортировка выглядит так и использует sortIndex

 public sortList = (a, b, order) => {

//here I use the index of the header to get the right data from the row
const firstCell = a.cells[this.sortIndex].text;
const secondCell = b.cells[this.sortIndex].text;
  if (order === 1) {
    if (firstCell < secondCell) {
    return -1;
    }
    if (firstCell > secondCell) {
    return 1;
    }
  }
  if (order === -1) {
    if (firstCell < secondCell) {
      return 1;
    }
    if (firstCell > secondCell) {
      return -1;
    }
  }
  return 0;
}
0 голосов
/ 30 июня 2018

есть способ индивидуального заказа:

import {HttpClient} from "aurelia-fetch-client";

export class Example {
    users = [];

    bind(){
        let client = new HttpClient();

        return client.fetch('data.json')
            .then(response => response.json())
            .then(users => this.users = users);
    }

    nameLength(row) {
        return row.name.length;
    }

    dateSort(a, b, sortOrder) {
        let date1 = new Date(a.registered);
        let date2 = new Date(b.registered);

        if (date1 === date2) {
            return 0;
        }

        if (date1 > date2) {
            return 1 * sortOrder;
        }

        return -1 * sortOrder;
    }
}
 .a ut-sort:before{
    font-family: FontAwesome;
    padding-right: 0.5em;
    width: 1.28571429em;
    display: inline-block;
    text-align: center;
}

.aut-sortable:before{
    content: "\f0dc";
}

.aut-asc:before{
    content: "\f160";
}

.aut-desc:before{
    content: "\f161";
}
<template>
    <table class="table table-striped" aurelia-table="data.bind: users; display-data.bind: $displayData">
        <thead>
        <tr>
            <th aut-sort="key.bind: nameLength">Name</th>
            <th aut-sort="key: age; default: desc">Age</th>
            <th>E-mail</th>
            <th aut-sort="custom.bind: dateSort">Registered</th>
            <th aut-sort="key: isActive">Active</th>
        </tr>
        </thead>
        <tbody>
        <tr repeat.for="user of $displayData">
            <td>${user.name}</td>
            <td>${user.age}</td>
            <td><a href="mailto:${user.email}">${user.email}</a></td>
            <td>${user.registered}</td>
            <td>${user.isActive}</td>
        </tr>
        </tbody>
    </table>
</template>
...