Using ECMAscript class as a source for datatable
Using ECMAscript class as a source for datatable
Evgeniy Vasyliev
Posts: 23Questions: 7Answers: 1
in General
Hi all!
I have a problem with filling my datatable with data.
Here is HTML markup:
<table id="employees" class="display w-100">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center">Position</th>
<th class="text-center">Salary</th>
<th class="text-center">Office </th>
<th class="text-center">Amount</th>
<th class="text-center">Price</th>
</tr>
</thead>
</table>
I tested 2 variants:
Variant 1 with standard javascript function (working fine):
function Employee ( name, position, salary, office ) {
this.name = name;
this.position = position;
this.salary = salary;
this.office = office;
};
table = $('#employees').DataTable({
dom: 't',
"ordering": false,
responsive: true,
select: true,
data: [
new Employee( "Tiger Nixon", "System Architect", "$3,120", "Edinburgh" ),
new Employee( "Garrett Winters", "Director", "$5,300", "Edinburgh" )
],
columns: [
{ data: 'name' },
{ data: 'salary' },
{ data: 'office' },
{ data: 'position' }
]
});
Here everything is working fine.
Variant 2 with ECMAscript classes sugar:
class Employee {
constructor(name, position, salary, office) {
this.name = name;
this.position = position;
this.salary = salary;
this.office = office;
}
get name() {
return this.name;
}
set name(name) {
this.name = name;
}
get position() {
return this.position;
}
set position(position) {
this.position = position;
}
get salary() {
return this.salary;
}
set salary(salary) {
this.salary = salary;
}
get office() {
return this.office;
}
set office(office) {
this.office = office;
}
};
table = $('#employees').DataTable({
dom: 't',
"ordering": false,
responsive: true,
select: true,
data: [
new Employee( "Tiger Nixon", "System Architect", "$3,120", "Edinburgh" ),
new Employee( "Garrett Winters", "Director", "$5,300", "Edinburgh" )
],
columns: [
{ data: 'name' },
{ data: 'salary' },
{ data: 'office' },
{ data: 'position' }
]
});
And it does not work! In console it gives an error "SyntaxError: redeclaration of let Employee"
Can you help if it can be solved and how?
Thanks!
This question has accepted answers - jump to:
This discussion has been closed.
Answers
Interesting, I never tried using ECMAscript classes. Looks like like
this.name
andname
are the same.The above results in this:
Changing all the
this.xxx
tothis._xxx
works. See this example:http://live.datatables.net/dutayuza/1/edit
Kevin
Thank you, Kevin! It helped a lot!
Nice one Kevin. It is worth noting as well that DataTables can also use methods as data points through the parenthesis syntax. E.g.
data: 'name()
(will see the()
and execute thename
method). The only thing it can't do is pass parameters.That said - I like using getters and setters better myself.
Allan