JSFiddle - React, Tailwind, and code Playground
HTML
Filter: <input id="filter"/>
<br/>
<div id="list">
<ul>
</ul>
</div>
Add user : <input id="in"/> <button id="ok">Ok</button>
JavaScript
var users = [{name: 'joe',id: 0}, {name: 'bob',id: 1}, {name: 'loic',id: 2}];
var lastId = 2;
fillList(users);
function addLine(user){
$('#list ul').append(
'<li id="'+user.id+'"><span>'+user.name+'</span><a class="del" href="#"> x</a></li>'
);
}
function fillList(list){
$("#list").html('<ul/>');
list.forEach(function(user){
addLine(user);
});
}
Array.observe(users, function(changes){
changes.forEach(function(change) {
if(change.type == "splice"){
//add
if(change.addedCount){
var index = change.index;
var user = users[index];
addLine(user);
}
//remove
else if(change.removed){
var id = change.removed[0].id;
$('li[id='+id+']').remove();
}
}
//update
else if(change.type == "update") {
var index = change.name;
var user = users[index];
$('li[id='+user.id+']').find("span").text(user.name);
}
});
});
function findIndex(id){
return users.map(function(x) {return x.id; }).indexOf(id);
}
//add
$("#ok").click(function(){
lastId +=1;
var name = $("#in").val();
var user = {name: name,id: lastId};
users.push(user);
});
//remove
$("#list").on("click", ".del", function(event) {
$("#filter").val("");
var id = parseInt($(this).parent().attr('id'),10);
var index = findIndex(id);
users.splice(index, 1);
});
//update
$("#list").on("click", "span", function(event) {
var input = $('<input />', {'type': 'text', 'name': 'edit', 'value': $(this).html()});
$(this).parent().append(input);
$(this).hide();
input.focus();
});
$("#list").on("blur", "input", function(event) {
$(this).parent().find("span").show();
var id = parseInt($(this).parent().attr('id'),10);
var index = findIndex(id);
users[index] = {name: $(this).val(), id: id};
...