Skip to content

Commit

Permalink
http://tech.colla.me/show/a_todo_app_premitive_implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Liu Shuo committed Nov 12, 2016
1 parent 62a8f16 commit b8347df
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
19 changes: 19 additions & 0 deletions app.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<h1>ToDO: <span class="jsCount">0</span></h1>
<ul class="jsList">
<li class="jsListEmpty">no item</li>
<script type="js/tmpl" id="js-tmpl-item">
<li>{this}<button class="jsDelete">x</button></li>
</script>
</ul>
<p><input type="text" class="jsInput"><button class="jsAdd">add</button></p>
</div>
<script src="./plain_2.js"></script>
</body>
</html>
57 changes: 57 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
(function(){
// rendering engine
var Render = function(selector, data){
var tmpl = document.querySelector(selector).innerHTML.trim();
var matches = tmpl.match(/<(\w+)>(.*)<\/(\w+)>/);
var newItem = document.createElement(matches[1]);
newItem.innerHTML = matches[2].replace('{this}', data);
return newItem;
};


// app
var $count = document.querySelector('.jsCount');
var $list = document.querySelector('.jsList');
var $listEmpty = document.querySelector('.jsListEmpty');
var $input = document.querySelector('.jsInput');
var $add = document.querySelector('.jsAdd');

var data = [];

var addItem = function(item){
data.push(item);
var newItem = Render('#js-tmpl-item', item);
newItem.querySelector('.jsDelete').addEventListener('click', function(){
removeItem(item);
$list.removeChild(newItem);
}, false);
$list.appendChild(newItem);
};

var removeItem = function(item){
data.splice(data.indexOf(item), 1);
updateCount();
};

var updateCount = function(){
$count.innerHTML = data.length;

if (data.length > 0){
$listEmpty.style.display = 'none';
} else {
$listEmpty.style.display = 'block';
}
};

var addHandler = function(){
var input = $input.value.trim();
if (input.length === 0){
return;
}
addItem(input);
$input.value = '';
updateCount();
};

$add.addEventListener('click', addHandler, false);
})();

0 comments on commit b8347df

Please sign in to comment.