Created
May 8, 2017 05:14
-
-
Save MrSkinny/f8a9720772ca760a363c51fd760364a2 to your computer and use it in GitHub Desktop.
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
const appState = { | |
items: [ | |
{ name: 'apples', checked: false }, | |
{ name: 'bananas', checked: true } | |
] | |
}; | |
// ============================ | |
// Item Creator | |
function createItem(itemName){ | |
return { name: itemName, checked: false }; | |
} | |
// ============================ | |
// State Modification Functions | |
function addItem(state, itemName){ | |
state.items.push(createItem(itemName)); | |
} | |
function removeItem(state, itemName){ | |
const targetInd = state.items.findIndex(i => i.name === itemName); | |
if (targetInd === -1) return false; | |
state.items.splice(targetInd, 1); | |
return true; | |
} | |
function toggleItem(state, itemName){ | |
const targetInd = state.items.findIndex(i => i.name === itemName); | |
if (targetInd === -1) return false; | |
state.items[targetInd].checked = !state.items[targetInd].checked | |
} | |
// ============================ | |
// Renderer Functions | |
function createItemHtml(item){ | |
return ` | |
<li> | |
<span class="shopping-item ${item.checked ? 'shopping-item__checked' : ''}">${item.name}</span> | |
<div class="shopping-item-controls"> | |
<button class="shopping-item-toggle"> | |
<span class="button-label">check</span> | |
</button> | |
<button class="shopping-item-delete"> | |
<span class="button-label">delete</span> | |
</button> | |
</div> | |
</li> | |
`; | |
} | |
function renderList(state, listEl){ | |
const html = state.items.map(i => createItemHtml(i)); | |
listEl.html(html); | |
} | |
// ============================= | |
// Event listeners | |
$('form').submit(e => { | |
e.preventDefault(); | |
addItem(appState, $('#shopping-list-entry').val()); | |
$('#shopping-list-entry').val(''); | |
renderList(appState, $('.shopping-list')); | |
}); | |
$('.shopping-list').on('click', '.shopping-item-toggle', e => { | |
const el = $(e.target); | |
const itemName = el.parent().parent().siblings('span').text(); | |
toggleItem(appState, itemName); | |
renderList(appState, $('.shopping-list')); | |
}); | |
$('.shopping-list').on('click', '.shopping-item-delete', e => { | |
const el = $(e.target); | |
const itemName = el.parent().parent().siblings('span').text(); | |
removeItem(appState, itemName); | |
renderList(appState, $('.shopping-list')); | |
}); | |
$(function(){ | |
renderList(appState, $('.shopping-list')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment