JSFiddle - React, Tailwind, and code Playground
HTML
<div id="list"></div>
<button id="move">Move last to beginning</button>
<button id="sort">Sort</button>
JavaScript
// Define collection
var models = [];
var moving = null; // Stores an info about element that is being moved
// Move items
function moveLastToBeginning() {
console.info('Move');
moving = {
from: models.length - 1,
to: 0
};
var item = models.pop();
models.unshift(item);
}
function sort() {
console.info('Sort');
models.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
}
// Observe changes
Array.observe(models, function (changes) {
console.log(changes);
changes.forEach(function (c) {
switch (c.type) {
case 'splice':
for (var i = c.removed.length - 1; i >= 0; i--) {
if (!moving) {
remove(c.index + i);
}
}
for (var i = 0; i < c.addedCount; i++) {
if (moving) {
move(moving.from, moving.to);
moving = null;
} else {
add(c.object[c.index + i], c.index + i);
}
}
break;
case 'update':
replace(c.object[c.name], c.name);
break;
default:
throw 'Not implemented';
}
});
});
//
// DOM
var list = document.getElementById('list');
document.getElementById('move').onclick = moveLastToBeginning;
document.getElementById('sort').onclick = sort;
//
// Manipulate DOM
function add(item, index) {
var element = document.createElement('div');
element.innerHTML = item.name;
if (index >= list.children.length) {
list.appendChild(element);
} else {
list.insertBefore(element, list.children[index]);
}
}
function remove(index) {
alert('Remove should not be called.');
list.removeChild(list.children[index]);
}
function replace(item, index) {
list.children[index].innerHTML = item.name;
}
function...