Ajout exo VanillaTodos

This commit is contained in:
wpetit 2015-04-01 11:17:02 +02:00 committed by Benjamin Bohard
parent 4a10785c1a
commit 482caf5b47
3 changed files with 159 additions and 0 deletions

View File

@ -0,0 +1,43 @@
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>Vanilla Todos</h1>
<div id="vanilla-todos">
<table>
<thead>
<tr>
<th colspan="2">
<input class="search-todos" type="text" placeholder="Filter todos..." />
</th>
</tr>
<tr>
<th>Todo</th>
<th>Actions</th>
</tr>
</thead>
<tbody class="todos-list">
<tr>
<td colspan="2">Aucune todo pour le moment !</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<input class="new-todo" type="text" />
</td>
</tr>
</tfoot>
</table>
</div>
</div>
<script src="vanilla-todos.js"></script>
<script>
(function() {
VanillaTodos.mount('#vanilla-todos');
}());
</script>
</body>
</html>

View File

@ -0,0 +1,4 @@
.container {
}

View File

@ -0,0 +1,112 @@
(function(VT, window) {
"use strict";
// Déclaration des variables
var _rootEl; // Élement racine de notre application
var _todos = []; // Notre liste de todos
// API publique
/*
* "Monte" l'application VanillaTodo sur l'élément du DOM
* correspondant au sélecteur CSS donné
*/
VT.mount = function(selector) {
_rootEl = window.document.querySelector(selector);
if(!_rootEl) {
throw new Error('Invalid selector "'+selector+'" !');
}
_initHandlers();
_renderTodos();
};
// API privée
function _initHandlers() {
var saveButton = _rootEl.querySelector('.new-todo');
saveButton.addEventListener('keydown', _saveNewTodoHandler);
var searchInput = _rootEl.querySelector('.search-todos');
searchInput.addEventListener('keyup', _searchInputChangeHandler);
//searchInput.addEventListener('change', _searchInputChangeHandler);
}
function _searchInputChangeHandler(evt) {
var searchInput = evt.currentTarget;
var searchText = searchInput.value.toLowerCase();
var todos;
if(searchText) {
todos = _todos.filter(function(todo) {
if(todo.text.toLowerCase().indexOf(searchText) !== -1) {
return true;
}
});
}
_renderTodos(todos);
}
function _saveNewTodoHandler(evt) {
if(evt.keyCode !== 13) return; // Enter
var newTodoInput = evt.currentTarget;
var todo = {
text: newTodoInput.value
};
newTodoInput.value = '';
_todos.push(todo);
_renderTodos(_todos);
}
function _renderTodos(todos) {
todos = todos || _todos;
var todosList = _rootEl.querySelector('.todos-list');
todosList.innerHTML = '';
todos.forEach(function(todo, i) {
var row = _createTodoRow(todo);
todosList.appendChild(row);
});
}
function _createTodoRow(todo) {
var row = document.createElement('tr');
row.appendChild( _createTodoCell(todo) );
row.appendChild( _createActionsCell(todo) );
return row;
}
function _createTodoCell(todo) {
var cell = document.createElement('td');
cell.innerHTML = todo.text;
return cell;
}
function _createActionsCell(todo) {
var cell = document.createElement('td');
return cell;
}
}(this.VanillaTodos = this.VanillaTodos || {}, window));