Skip to content

Instantly share code, notes, and snippets.

@h-sao
Created January 23, 2015 11:51
Show Gist options
  • Save h-sao/7655d3b019b25d3cd843 to your computer and use it in GitHub Desktop.
Save h-sao/7655d3b019b25d3cd843 to your computer and use it in GitHub Desktop.
VirtualDOMのハンズオン:index.html(要素を追加&削除するサンプル)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="virtualdom.js"></script>
<title></title>
</head>
<body>
<div>
<input type="text" name="todo" />
<button name="add" type="button">add</button>
</div>
<div class="list"></div>
<script>
var todos = [];
var textBox = document.querySelector("[name=todo]");
document.querySelector("[name=add]").addEventListener("click", function()
{
var todoText = textBox.value;
todos.push(todoText);
applyTodosVDom(todos);
}, false);
function applyTodosVDom(todolist)
{
var newTextVDOM = createVDom(todolist); //--- 新しいVirtual DOMを作る
var patch = virtualDom.diff(todoVDOM, newTextVDOM); //--- パッチを作る
todoNode = virtualDom.patch(todoNode, patch); //--- パッチ適用
todoVDOM = newTextVDOM;
}
function createVDom(todolist)
{
var textVDoms = todolist.map(function(todo, index)
{
return virtualDom.h("div", {}, [
virtualDom.h("button",
{
onclick: function()
{
todolist.splice(index, 1);
applyTodosVDom(todolist);
}
}),
virtualDom.h("span", {}, todo),
]);
});
return virtualDom.h("div", {}, textVDoms);
}
var todoVDOM = createVDom(todos); //--- VirtualDOM作成
var todoNode = virtualDom.create(todoVDOM); //--- DOM作成
document.querySelector(".list").appendChild(todoNode); //--- DOMツリーに追加
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment