Created
January 23, 2015 11:29
-
-
Save h-sao/a656b55a9928a8678a84 to your computer and use it in GitHub Desktop.
VirtualDOMのハンズオン:index.html(要素を追加するサンプル)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html xmlns="http://www.w3.org/1999/xhtml"> | |
<head> | |
<title></title> | |
<script src="virtualdom.js"></script> | |
</head> | |
<body> | |
<div> | |
<input type="text" name="todo" /> | |
<button name="add" type="button">add</button> | |
</div> | |
<div class="list"> | |
</div> | |
<script> | |
var todos = [], | |
textbox = document.querySelector("[name=todo]"); // Textbox | |
document.querySelector("[name=add]").addEventListener("click", function () { | |
var todoText = textbox.value; | |
todos.push(todoText); | |
var newTodoVDOM = createVDom(todos); // 新しいVirtualDOMを作る | |
var patch = virtualDom.diff(todoVDOM, newTodoVDOM); // パッチ作る | |
todoNode = virtualDom.patch(todoNode, patch); // パッチ適用 | |
todoVDOM = newTodoVDOM; | |
}, false) | |
// ここでVirtualDOMを組み立てる | |
function createVDom(todolist) { | |
var textVDoms = todolist.map(function (todo) { | |
return virtualDom.h("div", {}, [ | |
virtualDom.h("span", {}, todo) | |
]); | |
}); | |
return virtualDom.h("div", {}, textVDoms); | |
} | |
// createVDom()では、JavaScriptの世界で勝手に作ったDOMが出来ただけ | |
// これを、実際のHTMLが判断できるDOMにしてあげる必要がある | |
var todoVDOM = createVDom(todos); // VirtualDOM作成 | |
var todoNode = virtualDom.create(todoVDOM); // DOM作成 | |
document.querySelector(".list").appendChild(todoNode); // DOM Treeに追加 | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment