问题
I use the jQuery data tables plugin (https://datatables.net/).
You can use it on a html table like this:
$("#table").DataTable();
If I have a normal html table in my View and call the above in the attached()
method of my view model all works fine.
But things go wrong when I try to do this when generating the table from data I get from my API.
The table gets generated but under it instead of saying something like "showing 0 to 10 of 93 entries" it says "showing 0 to 0 of 0 entries". Also, if I try to sort the table by a given column all the data disappears leaving just the column headers.
UPDATE: I do not use any Ajax calls for sorting the table. I create my table from the data I get from my server. To elaborate: I get a json object from server. Use the json object to construct the table using "repeat.for='row of tableData' ". Calling the .DataTable() in attached hook creates the issue. I have tried creating a simple button that calls the .DataTable() method when clicked. It constructs the table properly. Seems like an issue with calling it in the attached() hook
回答1:
I agree with MJ, but you may be falling foul of timing issues.
Aurelia uses an async binding system which queues DOM updates to the micro task queue in order to batch them for performance reasons (that's why it's so quick)
You could try the following which should in theory allow any repeat bindings to be processed before your data tables are initialised.
import {TaskQueue} from 'aurelia-framework';
@inject(Element, TaskQueue)
export class DataTables {
constructor(element, taskQueue) {
this.element = element;
this.taskQueue = taskQueue;
}
attached() {
this.taskQueue.queueMicroTask(() => {
// Init data tables here
});
}
}
回答2:
You're going to want to create a custom element for your DataTable object. You're most likely going to want to use a custom binding on your DataTable element where you pass in the data. Lastly, you're going to want to call some kind of refresh or teardown/buildup function on your DataTable plugin in the "valueChanged" callback of the rows
binding.
dataTable.js
@inject(Element)
export class DataTableCustomElement {
element;
@bindable rows;
constructor(Element) {
this.element = $(Element);
}
rowsChanged(newValue, oldValue) {
this.element.DataTable.refresh(); // or whatever it is
}
}
view.html
<data-table rows.bind="data.rows"></data-table>
I dunno anything about your DataTable API. It may not have been designed to deal with new data coming from the server. I'll leave that to the reader.
来源:https://stackoverflow.com/questions/37530452/aurelia-data-disappears-in-table-when-using-datatables-jquery-plugin