JSFiddle - React, Tailwind, and code Playground
by ksumarine
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.11.5/vue.min.js"></script>
<table id="testTable">
<thead>
<tr>
<td><a href="#" data-sort="name">Name</a>
</td>
<td><a href="#" data-sort="age">Age</a>
</td>
<td><a href="#" data-sort="height">Height</a>
</td>
</tr>
</thead>
<tbody>
<tr v-repeat="testData | orderBy 'name'">
<td data-sort="name">{{name}}</td>
<td data-sort="age">{{age}}</td>
<td data-sort="height">{{height}}</td>
</tr>
</tbody>
</table>
<p>
<button>Reload</button>
</p>
CSS
table {
width:100%;
}
JavaScript
var data = [{
name: 'John',
age: 17.9,
height: 6.01
}, {
name: 'Bob',
age: 18.1,
height: 5.09
}, {
name: 'Sam',
age: 19.2,
height: 5.11
}, {
name: 'Frank',
age: 20.1,
height: 5.11
}];
makeData(data);
function makeData(_data) {
var vue = null;
vue = new Vue({
el: '#testTable',
data: {
title:'testData',
testData:_data
}
});
}
function sort_by(field, reverse, primer) {
var key = function (x) {
return primer ? primer(x[field]) : x[field]
};
return function (a, b) {
var A = key(a),
B = key(b);
return ((A < B) ? -1 : ((A > B) ? 1 : 0)) * [-1, 1][+ !! reverse];
}
}
$('button').unbind('click').bind('click', function (e) {
e.preventDefault();
var data2 = [{
name: 'Steve',
age: 18.9,
height: 6.00
}, {
name: 'Harry',
age: 17.1,
height: 5.07
}, {
name: 'Joe',
age: 19.2,
height: 5.08
}, {
name: 'Doug',
age: 21.1,
height: 5.08
}];
makeData(data2);
return false;
});
$('#testTable thead a').unbind('click').bind('click', function (e) {
e.preventDefault();
var thisSort = $(this).attr('data-sort');
var $headerLinks = $('#testTable thead a');
var sortArr = [];
//add/remove sorting classes from previous sort links
$headerLinks.not(this).removeClass('asc sort');
$(this).addClass('sort');
//if has asc, remove asc class
$(this).toggleClass('asc');
//get content of each td that matches the sort parameter and push it into an array
$('#testTable').find('td[data-sort="' + thisSort + '"]').each(function (index, el) {
sortArr.push({
sortVal: ($(el).hasClass('isdate') ? ($(el).text() !== '--' ? moment(new Date($(el).text())) : '') : $(el).text()),
ele: $(el).closest('tr')
});
});
//if the sorting link doesn't have...