我已經實施了簡單的待辦事項清單http://jsfiddle.net/tw9p9sw3/,並添加了可能的添加/刪除待辦事項。如何在Javascript中實現獨立組件?
(function (todoApp) {
'use strict';
todoApp.todoItemValue = '';
function _appendListNode() {
var listNode = document.createElement('li');
listNode.className = 'list-group-item';
listNode.appendChild(document.createTextNode(todoApp.todoItemValue));
listNode.appendChild(_createRemoveItemButton());
todoList.appendChild(listNode);
}
function _createRemoveItemButton() {
var removeButtonNode = document.createElement('a'),
removeButtonLabel = 'Remove';
removeButtonNode.className = 'badge';
removeButtonNode.appendChild(document.createTextNode(removeButtonLabel));
return removeButtonNode;
}
function _addItem() {
todoApp.todoItemValue = document.getElementById('todoInput').value;
_appendListNode();
document.getElementById('todoInput').value = '';
}
function _removeItem() {
var nodeToRemove = this.parentNode;
this.parentNode.parentNode.removeChild(nodeToRemove);
}
function _addEventHandlers() {
document.getElementById('todoListForm').addEventListener('submit', function (event) {
event.preventDefault();
_addItem();
});
/*
* Used delegated event cause todo list is not static,
* so we don't need to add events for remove buttons each time after DOM of todo list have changed
*/
document.getElementById('todoList').addEventListener('click', function (event) {
if (event.target && event.target.nodeName === 'A') {
event.preventDefault();
_removeItem.call(event.target);
}
});
}
todoApp.init = function() {
_addEventHandlers();
};
}(window.todoApp = window.todoApp || {}));
//////////////////////////////////////////////////////////
// INITIALIZATION
//////////////////////////////////////////////////////////
document.onload = todoApp.init();
的問題是,如何重新讓這個待辦事項列表作爲獨立的組件,這樣比如我可以在同一頁面上兩次注入/實例化它,應該有待辦事項列表實例之間沒有衝突。
有在Javascript中實現面向對象編程很多教程。 – Barmar