Ryddet kode

This commit is contained in:
Børge Antonsen 2018-10-19 17:23:42 +02:00
parent a4bc8585b7
commit 6af365f425
12 changed files with 291 additions and 452 deletions

View File

@ -1,20 +0,0 @@
.toggle-graph {
float: left;
margin-left: 16px;
cursor: pointer;
position: relative;
z-index: 1;
}
.toggle-graph svg {
height: 20px;
width: 20px;
}
.toggle-graph svg path {
fill: #777;
}
.toggle-graph.active svg path,
.toggle-graph:hover svg path,
.toggle-graph:focus svg path {
fill: black;
}

View File

@ -7,23 +7,21 @@ var Model = require('./model')
var Store = require('./store') var Store = require('./store')
var Template = require('./template') var Template = require('./template')
import {$on} from './helpers' /**
import {updateTodo} from './todo' * Sets up a brand new Todo list.
import toggleGraph from './graph' *
* @param {string} name The name of your new to do list.
export function onLoad() { // eslint-disable-line import/prefer-default-export */
updateTodo() function Todo(name) {
const toggleGraphButton = document.querySelector('.toggle-graph') this.storage = new Store(name)
$on( this.model = new Model(this.storage)
toggleGraphButton, this.template = new Template()
'click', this.view = new View(this.template)
() => { this.controller = new Controller(this.model, this.view)
const active = toggleGraph() }
if (active) {
toggleGraphButton.classList.add('active') module.exports.onLoad = function onLoad() {
} else { var todo = new Todo('todos-vanillajs')
toggleGraphButton.classList.remove('active') todo.controller.setView(document.location.hash)
} helpers.log('view set')
},
)
} }

View File

@ -1,4 +1,4 @@
export default Controller module.exports = Controller
/** /**
* Takes a model and view and acts as the controller between them * Takes a model and view and acts as the controller between them
@ -110,7 +110,7 @@ Controller.prototype.addItem = function(title) {
Controller.prototype.editItem = function(id) { Controller.prototype.editItem = function(id) {
var that = this var that = this
that.model.read(id, function(data) { that.model.read(id, function(data) {
that.view.render('editItem', {id, title: data[0].title}) that.view.render('editItem', {id: id, title: data[0].title})
}) })
} }
@ -120,8 +120,8 @@ Controller.prototype.editItem = function(id) {
Controller.prototype.editItemSave = function(id, title) { Controller.prototype.editItemSave = function(id, title) {
var that = this var that = this
if (title.trim()) { if (title.trim()) {
that.model.update(id, {title}, function() { that.model.update(id, {title: title}, function() {
that.view.render('editItemDone', {id, title}) that.view.render('editItemDone', {id: id, title: title})
}) })
} else { } else {
that.removeItem(id) that.removeItem(id)
@ -134,7 +134,7 @@ Controller.prototype.editItemSave = function(id, title) {
Controller.prototype.editItemCancel = function(id) { Controller.prototype.editItemCancel = function(id) {
var that = this var that = this
that.model.read(id, function(data) { that.model.read(id, function(data) {
that.view.render('editItemDone', {id, title: data[0].title}) that.view.render('editItemDone', {id: id, title: data[0].title})
}) })
} }
@ -179,10 +179,10 @@ Controller.prototype.removeCompletedItems = function() {
*/ */
Controller.prototype.toggleComplete = function(id, completed, silent) { Controller.prototype.toggleComplete = function(id, completed, silent) {
var that = this var that = this
that.model.update(id, {completed}, function() { that.model.update(id, {completed: completed}, function() {
that.view.render('elementComplete', { that.view.render('elementComplete', {
id, id: id,
completed, completed: completed
}) })
}) })
@ -230,7 +230,6 @@ Controller.prototype._updateCount = function() {
*/ */
Controller.prototype._filter = function(force) { Controller.prototype._filter = function(force) {
var activeRoute = this._activeRoute.charAt(0).toUpperCase() + this._activeRoute.substr(1) var activeRoute = this._activeRoute.charAt(0).toUpperCase() + this._activeRoute.substr(1)
// Update the elements on the page, which change with each completed todo // Update the elements on the page, which change with each completed todo
this._updateCount() this._updateCount()
@ -250,7 +249,6 @@ Controller.prototype._filter = function(force) {
Controller.prototype._updateFilterState = function(currentPage) { Controller.prototype._updateFilterState = function(currentPage) {
// Store a reference to the active route, allowing us to re-filter todo // Store a reference to the active route, allowing us to re-filter todo
// items as they are marked complete or incomplete. // items as they are marked complete or incomplete.
currentPage = currentPage.split('?')[0]
this._activeRoute = currentPage this._activeRoute = currentPage
if (currentPage === '') { if (currentPage === '') {

View File

@ -1,53 +0,0 @@
import {subscribe, getTodo} from '../todo'
let graphArea
const unsubscribe = {
store: null,
todo: null,
}
export default toggleGraph
function toggleGraph() {
if (graphArea) {
graphArea.remove()
graphArea = null
unsubscribe.store()
unsubscribe.todo()
return false
} else {
graphArea = document.createElement('div')
document.body.querySelector('.graph-area-container').appendChild(graphArea)
const {storage} = getTodo()
loadAndRenderGraph(graphArea, storage)
updateTodoSubscription()
updateStoreSubscription(storage)
return true
}
}
function updateTodoSubscription() {
if (unsubscribe.todo) {
unsubscribe.todo()
}
unsubscribe.todo = subscribe(function onTodoUpdate() {
const {storage} = getTodo()
updateStoreSubscription(storage)
loadAndRenderGraph(graphArea, storage)
})
}
function updateStoreSubscription(store) {
if (unsubscribe.store) {
unsubscribe.store()
}
unsubscribe.store = store.subscribe(function onStoreUpdate() {
loadAndRenderGraph(graphArea, store)
})
}
function loadAndRenderGraph(node, store) {
System.import('./render').then(({default: renderGraph}) => {
renderGraph(node, store)
})
}

View File

@ -1,44 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom'
import {PieChart} from 'rd3'
import {chain} from 'lodash'
export default updateGraph
function updateGraph(node, store) {
store.findAll(todos => {
ReactDOM.render(
<Graph todos={todos} />,
node,
)
})
}
function Graph({todos}) {
const data = chain(todos)
.groupBy('completed')
.map((group, complete) => ({
label: complete === 'true' ? 'Complete' : 'Incomplete',
value: Math.round(group.length / todos.length * 10000) / 100
}))
.value()
return (
<div>
There are {todos.length} total todos
<div>
<PieChart
data={data}
width={450}
height={310}
radius={110}
innerRadius={20}
sectorBorderColor="white"
title="Todo Data"
/>
</div>
</div>
)
}
Graph.propTypes = {
todos: React.PropTypes.array,
}

View File

@ -1,4 +1,4 @@
export {qs, qsa, $on, $delegate, $parent, remove} module.exports = {qs, qsa, log, $on, $delegate, $parent, remove, leftPad}
// Get element(s) by CSS selector: // Get element(s) by CSS selector:
function qs(selector, scope) { function qs(selector, scope) {
@ -9,6 +9,12 @@ function qsa(selector, scope) {
return (scope || document).querySelectorAll(selector) return (scope || document).querySelectorAll(selector)
} }
function log() {
if (window.console && window.console.log) {
window.console.log.apply(window.console, arguments) // eslint-disable-line
}
}
// addEventListener wrapper: // addEventListener wrapper:
function $on(target, type, callback, useCapture) { function $on(target, type, callback, useCapture) {
target.addEventListener(type, callback, !!useCapture) target.addEventListener(type, callback, !!useCapture)
@ -17,10 +23,6 @@ function $on(target, type, callback, useCapture) {
// Attach a handler to event for all elements that match the selector, // Attach a handler to event for all elements that match the selector,
// now or in the future, based on a root element // now or in the future, based on a root element
function $delegate(target, selector, type, handler) { function $delegate(target, selector, type, handler) {
// https://developer.mozilla.org/en-US/docs/Web/Events/blur
var useCapture = type === 'blur' || type === 'focus'
$on(target, type, dispatchEvent, useCapture)
function dispatchEvent(event) { function dispatchEvent(event) {
var targetElement = event.target var targetElement = event.target
var potentialElements = qsa(selector, target) var potentialElements = qsa(selector, target)
@ -30,13 +32,18 @@ function $delegate(target, selector, type, handler) {
handler.call(targetElement, event) handler.call(targetElement, event)
} }
} }
// https://developer.mozilla.org/en-US/docs/Web/Events/blur
var useCapture = type === 'blur' || type === 'focus'
$on(target, type, dispatchEvent, useCapture)
} }
// Find the element's parent with the given tag name: // Find the element's parent with the given tag name:
// $parent(qs('a'), 'div'); // $parent(qs('a'), 'div');
function $parent(element, tagName) { function $parent(element, tagName) {
if (!element.parentNode) { if (!element.parentNode) {
return undefined return
} }
if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) { if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
return element.parentNode return element.parentNode
@ -56,6 +63,16 @@ function remove(array, thing) {
array.splice(index, 1) array.splice(index, 1)
} }
// pad the left of the given string by the given size with the given character
// leftPad('10', 3, '0') -> 010
function leftPad(str, size, padWith) {
if (size <= str.length) {
return str
} else {
return Array(size - str.length + 1).join(padWith || '0') + str
}
}
// Allow for looping on nodes by chaining: // Allow for looping on nodes by chaining:
// qsa('.foo').forEach(function () {}) // qsa('.foo').forEach(function () {})
NodeList.prototype.forEach = Array.prototype.forEach NodeList.prototype.forEach = Array.prototype.forEach

6
src/index.html Normal file → Executable file
View File

@ -18,11 +18,6 @@
</section> </section>
<footer class="footer"> <footer class="footer">
<span class="todo-count"></span> <span class="todo-count"></span>
<button class="toggle-graph">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32">
<path d="M14 18v-14c-7.732 0-14 6.268-14 14s6.268 14 14 14 14-6.268 14-14c0-2.251-0.532-4.378-1.476-6.262l-12.524 6.262zM28.524 7.738c-2.299-4.588-7.043-7.738-12.524-7.738v14l12.524-6.262z"></path>
</svg>
</button>
<ul class="filters"> <ul class="filters">
<li> <li>
<a href="#/" class="selected">All</a> <a href="#/" class="selected">All</a>
@ -37,7 +32,6 @@
<button class="clear-completed">Clear completed</button> <button class="clear-completed">Clear completed</button>
</footer> </footer>
</section> </section>
<section class="graph-area-container"></section>
<footer class="info"> <footer class="info">
<p>Double-click to edit a todo</p> <p>Double-click to edit a todo</p>
<p>Created by <a href="http://twitter.com/oscargodson">Oscar Godson</a></p> <p>Created by <a href="http://twitter.com/oscargodson">Oscar Godson</a></p>

View File

@ -1,4 +1,4 @@
export default Model module.exports = Model
/** /**
* Creates a new Model instance and hooks up the storage. * Creates a new Model instance and hooks up the storage.
@ -30,19 +30,20 @@ Model.prototype.create = function(title, callback) {
} }
/** /**
* Finds and returns a model in storage. If no query is given it'll simply * Finds and returns a model in storage. If no query is given it'll simply
* return everything. If you pass in a string or number it'll look that up as * return everything. If you pass in a string or number it'll look that up as
* the ID of the model to find. Lastly, you can pass it an object to match against. * the ID of the model to find. Lastly, you can pass it an object to match
* * against.
* @param {string|number|object} [query] A query to match models against *
* @param {function} [callback] The callback to fire after the model is found * @param {string|number|object} [query] A query to match models against
* * @param {function} [callback] The callback to fire after the model is found
* @example *
* model.read(1, func); // Will find the model with an ID of 1 * @example
* model.read('1'); // Same as above * model.read(1, func); // Will find the model with an ID of 1
* //Below will find a model with foo equalling bar and hello equalling world. * model.read('1'); // Same as above
* model.read({ foo: 'bar', hello: 'world' }); * //Below will find a model with foo equalling bar and hello equalling world.
*/ * model.read({ foo: 'bar', hello: 'world' });
*/
Model.prototype.read = function(query, callback) { Model.prototype.read = function(query, callback) {
var queryType = typeof query var queryType = typeof query
callback = callback || function() { callback = callback || function() {
@ -57,7 +58,6 @@ Model.prototype.read = function(query, callback) {
} else { } else {
this.storage.find(query, callback) this.storage.find(query, callback)
} }
return undefined
} }
/** /**

View File

@ -1,14 +1,13 @@
import {remove} from './helpers' module.exports = Store
export default Store
/** /**
* Creates a new client side storage object and will create an empty * Creates a new client side storage object and will create an empty
* collection if no collection already exists. * collection if no collection already exists.
* *
* @param {string} name The name of our DB we want to use * @param {string} name The name of our DB we want to use
* @param {function} callback Our fake DB uses callbacks because in * @param {function} callback Our fake DB uses callbacks because in
* real life you probably would be making AJAX calls * real life you probably would be making AJAX calls
*/ */
function Store(name, callback) { function Store(name, callback) {
callback = callback || function() { callback = callback || function() {
} }
@ -24,16 +23,6 @@ function Store(name, callback) {
} }
callback.call(this, JSON.parse(localStorage[name])) callback.call(this, JSON.parse(localStorage[name]))
this.subscribers = []
}
Store.prototype.subscribe = function(subscriber) {
this.subscribers.push(subscriber)
return () => remove(this.subscribers, subscriber)
}
Store.prototype._notify = function() {
this.subscribers.forEach(s => s())
} }
/** /**
@ -45,8 +34,8 @@ Store.prototype._notify = function() {
* *
* @example * @example
* db.find({foo: 'bar', hello: 'world'}, function (data) { * db.find({foo: 'bar', hello: 'world'}, function (data) {
* // data will return any items that have foo: bar and * // data will return any items that have foo: bar and
* // hello: world in their properties * // hello: world in their properties
* }); * });
*/ */
Store.prototype.find = function(query, callback) { Store.prototype.find = function(query, callback) {
@ -96,8 +85,10 @@ Store.prototype.save = function(updateData, callback, id) {
if (id) { if (id) {
for (var i = 0; i < todos.length; i++) { for (var i = 0; i < todos.length; i++) {
if (todos[i].id === id) { if (todos[i].id === id) {
for (var key in updateData) { // eslint-disable-line guard-for-in for (var key in updateData) {
todos[i][key] = updateData[key] if (updateData.hasOwnProperty(key)) {
todos[i][key] = updateData[key]
}
} }
break break
} }
@ -113,7 +104,6 @@ Store.prototype.save = function(updateData, callback, id) {
localStorage[this._dbName] = JSON.stringify(data) localStorage[this._dbName] = JSON.stringify(data)
callback.call(this, [updateData]) callback.call(this, [updateData])
} }
this._notify()
} }
/** /**
@ -127,7 +117,7 @@ Store.prototype.remove = function(id, callback) {
var todos = data.todos var todos = data.todos
for (var i = 0; i < todos.length; i++) { for (var i = 0; i < todos.length; i++) {
if (todos[i].id === id) { if (todos[i].id == id) { // eslint-disable-line
todos.splice(i, 1) todos.splice(i, 1)
break break
} }
@ -135,7 +125,6 @@ Store.prototype.remove = function(id, callback) {
localStorage[this._dbName] = JSON.stringify(data) localStorage[this._dbName] = JSON.stringify(data)
callback.call(this, JSON.parse(localStorage[this._dbName]).todos) callback.call(this, JSON.parse(localStorage[this._dbName]).todos)
this._notify()
} }
/** /**
@ -146,5 +135,4 @@ Store.prototype.remove = function(id, callback) {
Store.prototype.drop = function(callback) { Store.prototype.drop = function(callback) {
localStorage[this._dbName] = JSON.stringify({todos: []}) localStorage[this._dbName] = JSON.stringify({todos: []})
callback.call(this, JSON.parse(localStorage[this._dbName]).todos) callback.call(this, JSON.parse(localStorage[this._dbName]).todos)
this._notify()
} }

View File

@ -1,4 +1,4 @@
export default Template module.exports = Template
var htmlEscapes = { var htmlEscapes = {
'&': '&amp;', '&': '&amp;',
@ -17,11 +17,9 @@ var reUnescapedHtml = /[&<>"'`]/g
var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source) var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source)
var escape = function(string) { var escape = function(string) {
if (string && reHasUnescapedHtml.test(string)) { return (string && reHasUnescapedHtml.test(string)) ?
return string.replace(reUnescapedHtml, escapeHtmlChar) string.replace(reUnescapedHtml, escapeHtmlChar) :
} else { string
return string
}
} }
/** /**
@ -30,34 +28,32 @@ var escape = function(string) {
* @constructor * @constructor
*/ */
function Template() { function Template() {
this.defaultTemplate = ` this.defaultTemplate = '<li data-id="{{id}}" class="{{completed}}">' +
<li data-id="{{id}}" class="{{completed}}"> '<div class="view">' +
<div class="view"> '<input class="toggle" type="checkbox" {{checked}}>' +
<input class="toggle" type="checkbox" {{checked}} /> '<label>{{title}}</label>' +
<label>{{title}}</label> '<button class="destroy"></button>' +
<button class="destroy"></button> '</div>' +
</div> '</li>'
</li>
`
} }
/** /**
* Creates an <li> HTML string and returns it for placement in your app. * Creates an <li> HTML string and returns it for placement in your app.
* *
* NOTE: In real life you should be using a templating engine such as Mustache * NOTE: In real life you should be using a templating engine such as Mustache
* or Handlebars, however, this is a vanilla JS example. * or Handlebars, however, this is a vanilla JS example.
* *
* @param {object} data The object containing keys you want to find in the * @param {object} data The object containing keys you want to find in the
* template to replace. * template to replace.
* @returns {string} HTML String of an <li> element * @returns {string} HTML String of an <li> element
* *
* @example * @example
* view.show({ * view.show({
* id: 1, * id: 1,
* title: "Hello World", * title: "Hello World",
* completed: 0, * completed: 0,
* }); * });
*/ */
Template.prototype.show = function(data) { Template.prototype.show = function(data) {
var i, l var i, l
var view = '' var view = ''
@ -84,11 +80,11 @@ Template.prototype.show = function(data) {
} }
/** /**
* Displays a counter of how many to dos are left to complete * Displays a counter of how many to dos are left to complete
* *
* @param {number} activeTodos The number of active todos. * @param {number} activeTodos The number of active todos.
* @returns {string} String containing the count * @returns {string} String containing the count
*/ */
Template.prototype.itemCounter = function(activeTodos) { Template.prototype.itemCounter = function(activeTodos) {
var plural = activeTodos === 1 ? '' : 's' var plural = activeTodos === 1 ? '' : 's'
@ -96,11 +92,11 @@ Template.prototype.itemCounter = function(activeTodos) {
} }
/** /**
* Updates the text within the "Clear completed" button * Updates the text within the "Clear completed" button
* *
* @param {[type]} completedTodos The number of completed todos. * @param {[type]} completedTodos The number of completed todos.
* @returns {string} String containing the count * @returns {string} String containing the count
*/ */
Template.prototype.clearCompletedButton = function(completedTodos) { Template.prototype.clearCompletedButton = function(completedTodos) {
if (completedTodos > 0) { if (completedTodos > 0) {
return 'Clear completed' return 'Clear completed'

View File

@ -1,41 +0,0 @@
import View from './view'
import Controller from './controller'
import Model from './model'
import Store from './store'
import Template from './template'
import {remove} from './helpers'
export {updateTodo, getTodo, subscribe}
let todo
const subscribers = []
/**
* Sets up a brand new Todo list.
*
* @param {string} name The name of your new to do list.
*/
function Todo(name) {
this.storage = new Store(name)
this.model = new Model(this.storage)
this.template = new Template()
this.view = new View(this.template)
this.controller = new Controller(this.model, this.view)
}
function updateTodo() {
todo = new Todo('todos-vanillajs')
todo.controller.setView(document.location.hash)
subscribers.forEach(s => s())
}
function getTodo() {
return todo
}
function subscribe(cb) {
subscribers.push(cb)
return function unsubscribe() {
remove(subscribers, cb)
}
}

View File

@ -1,184 +1,57 @@
/* eslint no-invalid-this: 0, complexity:[2, 9] */ /* eslint no-invalid-this: 0 */
import {qs, qsa, $on, $parent, $delegate} from './helpers'
var helpers = require('./helpers')
var qs = helpers.qs
var qsa = helpers.qsa
var $on = helpers.$on
var $parent = helpers.$parent
var $delegate = helpers.$delegate
module.exports = View
/** /**
* View that abstracts away the browser's DOM completely. * View that abstracts away the browser's DOM completely.
* It has two simple entry points: * It has two simple entry points:
* *
* - bind(eventName, handler) * - bind(eventName, handler)
* Takes a todo application event and registers the handler * Takes a todo application event and registers the handler
* - render(command, parameterObject) * - render(command, parameterObject)
* Renders the given command with the options * Renders the given command with the options
*/ */
export default class View { function View(template) {
constructor(template) { this.template = template
this.template = template
this.ENTER_KEY = 13 this.ENTER_KEY = 13
this.ESCAPE_KEY = 27 this.ESCAPE_KEY = 27
this.$todoList = qs('.todo-list') this.$todoList = qs('.todo-list')
this.$todoItemCounter = qs('.todo-count') this.$todoItemCounter = qs('.todo-count')
this.$clearCompleted = qs('.clear-completed') this.$clearCompleted = qs('.clear-completed')
this.$main = qs('.main') this.$main = qs('.main')
this.$footer = qs('.footer') this.$footer = qs('.footer')
this.$toggleAll = qs('.toggle-all') this.$toggleAll = qs('.toggle-all')
this.$newTodo = qs('.new-todo') this.$newTodo = qs('.new-todo')
} }
_removeItem(id) { View.prototype._removeItem = function(id) {
var elem = qs('[data-id="' + id + '"]') var elem = qs('[data-id="' + id + '"]')
if (elem) { if (elem) {
this.$todoList.removeChild(elem) this.$todoList.removeChild(elem)
}
}
_clearCompletedButton(completedCount, visible) {
this.$clearCompleted.innerHTML = this.template.clearCompletedButton(completedCount)
this.$clearCompleted.style.display = visible ? 'block' : 'none'
}
_editItemDone(id, title) {
var listItem = qs('[data-id="' + id + '"]')
if (!listItem) {
return
}
var input = qs('input.edit', listItem)
listItem.removeChild(input)
listItem.className = listItem.className.replace('editing', '')
qsa('label', listItem).forEach(function(label) {
label.textContent = title
})
}
render(viewCmd, parameter) {
var that = this
var viewCommands = {
showEntries: function() {
that.$todoList.innerHTML = that.template.show(parameter)
},
removeItem: function() {
that._removeItem(parameter)
},
updateElementCount: function() {
that.$todoItemCounter.innerHTML = that.template.itemCounter(parameter)
},
clearCompletedButton: function() {
that._clearCompletedButton(parameter.completed, parameter.visible)
},
contentBlockVisibility: function() {
that.$main.style.display = that.$footer.style.display = parameter.visible ? 'block' : 'none'
},
toggleAll: function() {
that.$toggleAll.checked = parameter.checked
},
setFilter: function() {
_setFilter(parameter)
},
clearNewTodo: function() {
that.$newTodo.value = ''
},
elementComplete: function() {
_elementComplete(parameter.id, parameter.completed)
},
editItem: function() {
_editItem(parameter.id, parameter.title)
},
editItemDone: function() {
that._editItemDone(parameter.id, parameter.title)
}
}
viewCommands[viewCmd]()
}
_bindItemEditDone(handler) {
var that = this
$delegate(that.$todoList, 'li .edit', 'blur', function() {
if (!this.dataset.iscanceled) {
handler({
id: _itemId(this),
title: this.value
})
}
})
$delegate(that.$todoList, 'li .edit', 'keypress', function(event) {
if (event.keyCode === that.ENTER_KEY) {
// Remove the cursor from the input when you hit enter just like if it
// were a real form
this.blur()
}
})
}
_bindItemEditCancel(handler) {
var that = this
$delegate(that.$todoList, 'li .edit', 'keyup', function(event) {
if (event.keyCode === that.ESCAPE_KEY) {
this.dataset.iscanceled = true
this.blur()
handler({id: _itemId(this)})
}
})
}
bind(event, handler) {
var that = this
if (event === 'newTodo') {
$on(that.$newTodo, 'change', function() {
handler(that.$newTodo.value)
})
} else if (event === 'removeCompleted') {
$on(that.$clearCompleted, 'click', function() {
handler()
})
} else if (event === 'toggleAll') {
$on(that.$toggleAll, 'click', function() {
handler({completed: this.checked})
})
} else if (event === 'itemEdit') {
$delegate(that.$todoList, 'li label', 'dblclick', function() {
handler({id: _itemId(this)})
})
} else if (event === 'itemRemove') {
$delegate(that.$todoList, '.destroy', 'click', function() {
handler({id: _itemId(this)})
})
} else if (event === 'itemToggle') {
$delegate(that.$todoList, '.toggle', 'click', function() {
handler({
id: _itemId(this),
completed: this.checked
})
})
} else if (event === 'itemEditDone') {
that._bindItemEditDone(handler)
} else if (event === 'itemEditCancel') {
that._bindItemEditCancel(handler)
}
} }
} }
function _setFilter(currentPage) { View.prototype._clearCompletedButton = function(completedCount, visible) {
this.$clearCompleted.innerHTML = this.template.clearCompletedButton(completedCount)
this.$clearCompleted.style.display = visible ? 'block' : 'none'
}
View.prototype._setFilter = function(currentPage) {
qs('.filters .selected').className = '' qs('.filters .selected').className = ''
qs('.filters [href="#/' + currentPage + '"]').className = 'selected' qs('.filters [href="#/' + currentPage + '"]').className = 'selected'
} }
function _elementComplete(id, completed) { View.prototype._elementComplete = function(id, completed) {
var listItem = qs('[data-id="' + id + '"]') var listItem = qs('[data-id="' + id + '"]')
if (!listItem) { if (!listItem) {
@ -191,7 +64,7 @@ function _elementComplete(id, completed) {
qs('input', listItem).checked = completed qs('input', listItem).checked = completed
} }
function _editItem(id, title) { View.prototype._editItem = function(id, title) {
var listItem = qs('[data-id="' + id + '"]') var listItem = qs('[data-id="' + id + '"]')
if (!listItem) { if (!listItem) {
@ -208,7 +81,140 @@ function _editItem(id, title) {
input.value = title input.value = title
} }
function _itemId(element) { View.prototype._editItemDone = function(id, title) {
var listItem = qs('[data-id="' + id + '"]')
if (!listItem) {
return
}
var input = qs('input.edit', listItem)
listItem.removeChild(input)
listItem.className = listItem.className.replace('editing', '')
qsa('label', listItem).forEach(function(label) {
label.textContent = title
})
}
View.prototype.render = function(viewCmd, parameter) {
var that = this
var viewCommands = {
showEntries: function() {
that.$todoList.innerHTML = that.template.show(parameter)
},
removeItem: function() {
that._removeItem(parameter)
},
updateElementCount: function() {
that.$todoItemCounter.innerHTML = that.template.itemCounter(parameter)
},
clearCompletedButton: function() {
that._clearCompletedButton(parameter.completed, parameter.visible)
},
contentBlockVisibility: function() {
that.$main.style.display = that.$footer.style.display = parameter.visible ? 'block' : 'none'
},
toggleAll: function() {
that.$toggleAll.checked = parameter.checked
},
setFilter: function() {
that._setFilter(parameter)
},
clearNewTodo: function() {
that.$newTodo.value = ''
},
elementComplete: function() {
that._elementComplete(parameter.id, parameter.completed)
},
editItem: function() {
that._editItem(parameter.id, parameter.title)
},
editItemDone: function() {
that._editItemDone(parameter.id, parameter.title)
}
}
viewCommands[viewCmd]()
}
View.prototype._itemId = function(element) {
var li = $parent(element, 'li') var li = $parent(element, 'li')
return parseInt(li.dataset.id, 10) return parseInt(li.dataset.id, 10)
} }
View.prototype._bindItemEditDone = function(handler) {
var that = this
$delegate(that.$todoList, 'li .edit', 'blur', function() {
if (!this.dataset.iscanceled) {
handler({
id: that._itemId(this),
title: this.value
})
}
})
$delegate(that.$todoList, 'li .edit', 'keypress', function(event) {
if (event.keyCode === that.ENTER_KEY) {
// Remove the cursor from the input when you hit enter just like if it
// were a real form
this.blur()
}
})
}
View.prototype._bindItemEditCancel = function(handler) {
var that = this
$delegate(that.$todoList, 'li .edit', 'keyup', function(event) {
if (event.keyCode === that.ESCAPE_KEY) {
this.dataset.iscanceled = true
this.blur()
handler({id: that._itemId(this)})
}
})
}
View.prototype.bind = function(event, handler) { // eslint-disable-line
var that = this
if (event === 'newTodo') {
$on(that.$newTodo, 'change', function() {
handler(that.$newTodo.value)
})
} else if (event === 'removeCompleted') {
$on(that.$clearCompleted, 'click', function() {
handler()
})
} else if (event === 'toggleAll') {
$on(that.$toggleAll, 'click', function() {
handler({completed: this.checked})
})
} else if (event === 'itemEdit') {
$delegate(that.$todoList, 'li label', 'dblclick', function() {
handler({id: that._itemId(this)})
})
} else if (event === 'itemRemove') {
$delegate(that.$todoList, '.destroy', 'click', function() {
handler({id: that._itemId(this)})
})
} else if (event === 'itemToggle') {
$delegate(that.$todoList, '.toggle', 'click', function() {
handler({
id: that._itemId(this),
completed: this.checked
})
})
} else if (event === 'itemEditDone') {
that._bindItemEditDone(handler)
} else if (event === 'itemEditCancel') {
that._bindItemEditCancel(handler)
}
}