Ryddet kode
This commit is contained in:
parent
a4bc8585b7
commit
6af365f425
20
src/app.css
20
src/app.css
@ -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;
|
||||
}
|
||||
36
src/app.js
36
src/app.js
@ -7,23 +7,21 @@ var Model = require('./model')
|
||||
var Store = require('./store')
|
||||
var Template = require('./template')
|
||||
|
||||
import {$on} from './helpers'
|
||||
import {updateTodo} from './todo'
|
||||
import toggleGraph from './graph'
|
||||
|
||||
export function onLoad() { // eslint-disable-line import/prefer-default-export
|
||||
updateTodo()
|
||||
const toggleGraphButton = document.querySelector('.toggle-graph')
|
||||
$on(
|
||||
toggleGraphButton,
|
||||
'click',
|
||||
() => {
|
||||
const active = toggleGraph()
|
||||
if (active) {
|
||||
toggleGraphButton.classList.add('active')
|
||||
} else {
|
||||
toggleGraphButton.classList.remove('active')
|
||||
}
|
||||
},
|
||||
)
|
||||
/**
|
||||
* 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)
|
||||
}
|
||||
|
||||
module.exports.onLoad = function onLoad() {
|
||||
var todo = new Todo('todos-vanillajs')
|
||||
todo.controller.setView(document.location.hash)
|
||||
helpers.log('view set')
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
export default Controller
|
||||
module.exports = Controller
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
var that = this
|
||||
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) {
|
||||
var that = this
|
||||
if (title.trim()) {
|
||||
that.model.update(id, {title}, function() {
|
||||
that.view.render('editItemDone', {id, title})
|
||||
that.model.update(id, {title: title}, function() {
|
||||
that.view.render('editItemDone', {id: id, title: title})
|
||||
})
|
||||
} else {
|
||||
that.removeItem(id)
|
||||
@ -134,7 +134,7 @@ Controller.prototype.editItemSave = function(id, title) {
|
||||
Controller.prototype.editItemCancel = function(id) {
|
||||
var that = this
|
||||
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) {
|
||||
var that = this
|
||||
that.model.update(id, {completed}, function() {
|
||||
that.model.update(id, {completed: completed}, function() {
|
||||
that.view.render('elementComplete', {
|
||||
id,
|
||||
completed,
|
||||
id: id,
|
||||
completed: completed
|
||||
})
|
||||
})
|
||||
|
||||
@ -230,7 +230,6 @@ Controller.prototype._updateCount = function() {
|
||||
*/
|
||||
Controller.prototype._filter = function(force) {
|
||||
var activeRoute = this._activeRoute.charAt(0).toUpperCase() + this._activeRoute.substr(1)
|
||||
|
||||
// Update the elements on the page, which change with each completed todo
|
||||
this._updateCount()
|
||||
|
||||
@ -250,7 +249,6 @@ Controller.prototype._filter = function(force) {
|
||||
Controller.prototype._updateFilterState = function(currentPage) {
|
||||
// Store a reference to the active route, allowing us to re-filter todo
|
||||
// items as they are marked complete or incomplete.
|
||||
currentPage = currentPage.split('?')[0]
|
||||
this._activeRoute = currentPage
|
||||
|
||||
if (currentPage === '') {
|
||||
|
||||
@ -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)
|
||||
})
|
||||
}
|
||||
@ -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,
|
||||
}
|
||||
@ -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:
|
||||
function qs(selector, scope) {
|
||||
@ -9,6 +9,12 @@ function qsa(selector, scope) {
|
||||
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:
|
||||
function $on(target, 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,
|
||||
// now or in the future, based on a root element
|
||||
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) {
|
||||
var targetElement = event.target
|
||||
var potentialElements = qsa(selector, target)
|
||||
@ -30,13 +32,18 @@ function $delegate(target, selector, type, handler) {
|
||||
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:
|
||||
// $parent(qs('a'), 'div');
|
||||
function $parent(element, tagName) {
|
||||
if (!element.parentNode) {
|
||||
return undefined
|
||||
return
|
||||
}
|
||||
if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
|
||||
return element.parentNode
|
||||
@ -56,6 +63,16 @@ function remove(array, thing) {
|
||||
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:
|
||||
// qsa('.foo').forEach(function () {})
|
||||
NodeList.prototype.forEach = Array.prototype.forEach
|
||||
|
||||
6
src/index.html
Normal file → Executable file
6
src/index.html
Normal file → Executable file
@ -18,11 +18,6 @@
|
||||
</section>
|
||||
<footer class="footer">
|
||||
<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">
|
||||
<li>
|
||||
<a href="#/" class="selected">All</a>
|
||||
@ -37,7 +32,6 @@
|
||||
<button class="clear-completed">Clear completed</button>
|
||||
</footer>
|
||||
</section>
|
||||
<section class="graph-area-container"></section>
|
||||
<footer class="info">
|
||||
<p>Double-click to edit a todo</p>
|
||||
<p>Created by <a href="http://twitter.com/oscargodson">Oscar Godson</a></p>
|
||||
|
||||
30
src/model.js
30
src/model.js
@ -1,4 +1,4 @@
|
||||
export default Model
|
||||
module.exports = Model
|
||||
|
||||
/**
|
||||
* 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
|
||||
* 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.
|
||||
*
|
||||
* @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
|
||||
* model.read('1'); // Same as above
|
||||
* //Below will find a model with foo equalling bar and hello equalling world.
|
||||
* model.read({ foo: 'bar', hello: 'world' });
|
||||
*/
|
||||
* 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
|
||||
* 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
|
||||
*
|
||||
* @example
|
||||
* model.read(1, func); // Will find the model with an ID of 1
|
||||
* model.read('1'); // Same as above
|
||||
* //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) {
|
||||
var queryType = typeof query
|
||||
callback = callback || function() {
|
||||
@ -57,7 +58,6 @@ Model.prototype.read = function(query, callback) {
|
||||
} else {
|
||||
this.storage.find(query, callback)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
36
src/store.js
36
src/store.js
@ -1,14 +1,13 @@
|
||||
import {remove} from './helpers'
|
||||
export default Store
|
||||
module.exports = Store
|
||||
|
||||
/**
|
||||
* Creates a new client side storage object and will create an empty
|
||||
* collection if no collection already exists.
|
||||
*
|
||||
* @param {string} name The name of our DB we want to use
|
||||
* @param {function} callback Our fake DB uses callbacks because in
|
||||
* real life you probably would be making AJAX calls
|
||||
*/
|
||||
* Creates a new client side storage object and will create an empty
|
||||
* collection if no collection already exists.
|
||||
*
|
||||
* @param {string} name The name of our DB we want to use
|
||||
* @param {function} callback Our fake DB uses callbacks because in
|
||||
* real life you probably would be making AJAX calls
|
||||
*/
|
||||
function Store(name, callback) {
|
||||
callback = callback || function() {
|
||||
}
|
||||
@ -24,16 +23,6 @@ function Store(name, callback) {
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
/**
|
||||
@ -96,9 +85,11 @@ Store.prototype.save = function(updateData, callback, id) {
|
||||
if (id) {
|
||||
for (var i = 0; i < todos.length; i++) {
|
||||
if (todos[i].id === id) {
|
||||
for (var key in updateData) { // eslint-disable-line guard-for-in
|
||||
for (var key in updateData) {
|
||||
if (updateData.hasOwnProperty(key)) {
|
||||
todos[i][key] = updateData[key]
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
@ -113,7 +104,6 @@ Store.prototype.save = function(updateData, callback, id) {
|
||||
localStorage[this._dbName] = JSON.stringify(data)
|
||||
callback.call(this, [updateData])
|
||||
}
|
||||
this._notify()
|
||||
}
|
||||
|
||||
/**
|
||||
@ -127,7 +117,7 @@ Store.prototype.remove = function(id, callback) {
|
||||
var todos = data.todos
|
||||
|
||||
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)
|
||||
break
|
||||
}
|
||||
@ -135,7 +125,6 @@ Store.prototype.remove = function(id, callback) {
|
||||
|
||||
localStorage[this._dbName] = JSON.stringify(data)
|
||||
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) {
|
||||
localStorage[this._dbName] = JSON.stringify({todos: []})
|
||||
callback.call(this, JSON.parse(localStorage[this._dbName]).todos)
|
||||
this._notify()
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
export default Template
|
||||
module.exports = Template
|
||||
|
||||
var htmlEscapes = {
|
||||
'&': '&',
|
||||
@ -17,11 +17,9 @@ var reUnescapedHtml = /[&<>"'`]/g
|
||||
var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source)
|
||||
|
||||
var escape = function(string) {
|
||||
if (string && reHasUnescapedHtml.test(string)) {
|
||||
return string.replace(reUnescapedHtml, escapeHtmlChar)
|
||||
} else {
|
||||
return string
|
||||
}
|
||||
return (string && reHasUnescapedHtml.test(string)) ?
|
||||
string.replace(reUnescapedHtml, escapeHtmlChar) :
|
||||
string
|
||||
}
|
||||
|
||||
/**
|
||||
@ -30,34 +28,32 @@ var escape = function(string) {
|
||||
* @constructor
|
||||
*/
|
||||
function Template() {
|
||||
this.defaultTemplate = `
|
||||
<li data-id="{{id}}" class="{{completed}}">
|
||||
<div class="view">
|
||||
<input class="toggle" type="checkbox" {{checked}} />
|
||||
<label>{{title}}</label>
|
||||
<button class="destroy"></button>
|
||||
</div>
|
||||
</li>
|
||||
`
|
||||
this.defaultTemplate = '<li data-id="{{id}}" class="{{completed}}">' +
|
||||
'<div class="view">' +
|
||||
'<input class="toggle" type="checkbox" {{checked}}>' +
|
||||
'<label>{{title}}</label>' +
|
||||
'<button class="destroy"></button>' +
|
||||
'</div>' +
|
||||
'</li>'
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* or Handlebars, however, this is a vanilla JS example.
|
||||
*
|
||||
* @param {object} data The object containing keys you want to find in the
|
||||
* template to replace.
|
||||
* @returns {string} HTML String of an <li> element
|
||||
*
|
||||
* @example
|
||||
* view.show({
|
||||
* id: 1,
|
||||
* title: "Hello World",
|
||||
* completed: 0,
|
||||
* });
|
||||
*/
|
||||
* 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
|
||||
* or Handlebars, however, this is a vanilla JS example.
|
||||
*
|
||||
* @param {object} data The object containing keys you want to find in the
|
||||
* template to replace.
|
||||
* @returns {string} HTML String of an <li> element
|
||||
*
|
||||
* @example
|
||||
* view.show({
|
||||
* id: 1,
|
||||
* title: "Hello World",
|
||||
* completed: 0,
|
||||
* });
|
||||
*/
|
||||
Template.prototype.show = function(data) {
|
||||
var i, l
|
||||
var view = ''
|
||||
@ -84,11 +80,11 @@ Template.prototype.show = function(data) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a counter of how many to dos are left to complete
|
||||
*
|
||||
* @param {number} activeTodos The number of active todos.
|
||||
* @returns {string} String containing the count
|
||||
*/
|
||||
* Displays a counter of how many to dos are left to complete
|
||||
*
|
||||
* @param {number} activeTodos The number of active todos.
|
||||
* @returns {string} String containing the count
|
||||
*/
|
||||
Template.prototype.itemCounter = function(activeTodos) {
|
||||
var plural = activeTodos === 1 ? '' : 's'
|
||||
|
||||
@ -96,11 +92,11 @@ Template.prototype.itemCounter = function(activeTodos) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the text within the "Clear completed" button
|
||||
*
|
||||
* @param {[type]} completedTodos The number of completed todos.
|
||||
* @returns {string} String containing the count
|
||||
*/
|
||||
* Updates the text within the "Clear completed" button
|
||||
*
|
||||
* @param {[type]} completedTodos The number of completed todos.
|
||||
* @returns {string} String containing the count
|
||||
*/
|
||||
Template.prototype.clearCompletedButton = function(completedTodos) {
|
||||
if (completedTodos > 0) {
|
||||
return 'Clear completed'
|
||||
|
||||
41
src/todo.js
41
src/todo.js
@ -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)
|
||||
}
|
||||
}
|
||||
154
src/view.js
154
src/view.js
@ -1,17 +1,24 @@
|
||||
/* eslint no-invalid-this: 0, complexity:[2, 9] */
|
||||
import {qs, qsa, $on, $parent, $delegate} from './helpers'
|
||||
/* eslint no-invalid-this: 0 */
|
||||
|
||||
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.
|
||||
* It has two simple entry points:
|
||||
*
|
||||
* - bind(eventName, handler)
|
||||
* Takes a todo application event and registers the handler
|
||||
* - render(command, parameterObject)
|
||||
* Renders the given command with the options
|
||||
*/
|
||||
export default class View {
|
||||
constructor(template) {
|
||||
* View that abstracts away the browser's DOM completely.
|
||||
* It has two simple entry points:
|
||||
*
|
||||
* - bind(eventName, handler)
|
||||
* Takes a todo application event and registers the handler
|
||||
* - render(command, parameterObject)
|
||||
* Renders the given command with the options
|
||||
*/
|
||||
function View(template) {
|
||||
this.template = template
|
||||
|
||||
this.ENTER_KEY = 13
|
||||
@ -24,22 +31,57 @@ export default class View {
|
||||
this.$footer = qs('.footer')
|
||||
this.$toggleAll = qs('.toggle-all')
|
||||
this.$newTodo = qs('.new-todo')
|
||||
}
|
||||
}
|
||||
|
||||
_removeItem(id) {
|
||||
View.prototype._removeItem = function(id) {
|
||||
var elem = qs('[data-id="' + id + '"]')
|
||||
|
||||
if (elem) {
|
||||
this.$todoList.removeChild(elem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_clearCompletedButton(completedCount, visible) {
|
||||
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 [href="#/' + currentPage + '"]').className = 'selected'
|
||||
}
|
||||
|
||||
View.prototype._elementComplete = function(id, completed) {
|
||||
var listItem = qs('[data-id="' + id + '"]')
|
||||
|
||||
if (!listItem) {
|
||||
return
|
||||
}
|
||||
|
||||
_editItemDone(id, title) {
|
||||
listItem.className = completed ? 'completed' : ''
|
||||
|
||||
// In case it was toggled from an event and not by clicking the checkbox
|
||||
qs('input', listItem).checked = completed
|
||||
}
|
||||
|
||||
View.prototype._editItem = function(id, title) {
|
||||
var listItem = qs('[data-id="' + id + '"]')
|
||||
|
||||
if (!listItem) {
|
||||
return
|
||||
}
|
||||
|
||||
listItem.className = listItem.className + ' editing'
|
||||
|
||||
var input = document.createElement('input')
|
||||
input.className = 'edit'
|
||||
|
||||
listItem.appendChild(input)
|
||||
input.focus()
|
||||
input.value = title
|
||||
}
|
||||
|
||||
View.prototype._editItemDone = function(id, title) {
|
||||
var listItem = qs('[data-id="' + id + '"]')
|
||||
|
||||
if (!listItem) {
|
||||
@ -54,9 +96,9 @@ export default class View {
|
||||
qsa('label', listItem).forEach(function(label) {
|
||||
label.textContent = title
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
render(viewCmd, parameter) {
|
||||
View.prototype.render = function(viewCmd, parameter) {
|
||||
var that = this
|
||||
var viewCommands = {
|
||||
showEntries: function() {
|
||||
@ -78,16 +120,16 @@ export default class View {
|
||||
that.$toggleAll.checked = parameter.checked
|
||||
},
|
||||
setFilter: function() {
|
||||
_setFilter(parameter)
|
||||
that._setFilter(parameter)
|
||||
},
|
||||
clearNewTodo: function() {
|
||||
that.$newTodo.value = ''
|
||||
},
|
||||
elementComplete: function() {
|
||||
_elementComplete(parameter.id, parameter.completed)
|
||||
that._elementComplete(parameter.id, parameter.completed)
|
||||
},
|
||||
editItem: function() {
|
||||
_editItem(parameter.id, parameter.title)
|
||||
that._editItem(parameter.id, parameter.title)
|
||||
},
|
||||
editItemDone: function() {
|
||||
that._editItemDone(parameter.id, parameter.title)
|
||||
@ -95,14 +137,19 @@ export default class View {
|
||||
}
|
||||
|
||||
viewCommands[viewCmd]()
|
||||
}
|
||||
}
|
||||
|
||||
_bindItemEditDone(handler) {
|
||||
View.prototype._itemId = function(element) {
|
||||
var li = $parent(element, 'li')
|
||||
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: _itemId(this),
|
||||
id: that._itemId(this),
|
||||
title: this.value
|
||||
})
|
||||
}
|
||||
@ -115,21 +162,21 @@ export default class View {
|
||||
this.blur()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
_bindItemEditCancel(handler) {
|
||||
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: _itemId(this)})
|
||||
handler({id: that._itemId(this)})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
bind(event, handler) {
|
||||
View.prototype.bind = function(event, handler) { // eslint-disable-line
|
||||
var that = this
|
||||
if (event === 'newTodo') {
|
||||
$on(that.$newTodo, 'change', function() {
|
||||
@ -148,18 +195,18 @@ export default class View {
|
||||
|
||||
} else if (event === 'itemEdit') {
|
||||
$delegate(that.$todoList, 'li label', 'dblclick', function() {
|
||||
handler({id: _itemId(this)})
|
||||
handler({id: that._itemId(this)})
|
||||
})
|
||||
|
||||
} else if (event === 'itemRemove') {
|
||||
$delegate(that.$todoList, '.destroy', 'click', function() {
|
||||
handler({id: _itemId(this)})
|
||||
handler({id: that._itemId(this)})
|
||||
})
|
||||
|
||||
} else if (event === 'itemToggle') {
|
||||
$delegate(that.$todoList, '.toggle', 'click', function() {
|
||||
handler({
|
||||
id: _itemId(this),
|
||||
id: that._itemId(this),
|
||||
completed: this.checked
|
||||
})
|
||||
})
|
||||
@ -170,45 +217,4 @@ export default class View {
|
||||
} else if (event === 'itemEditCancel') {
|
||||
that._bindItemEditCancel(handler)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _setFilter(currentPage) {
|
||||
qs('.filters .selected').className = ''
|
||||
qs('.filters [href="#/' + currentPage + '"]').className = 'selected'
|
||||
}
|
||||
|
||||
function _elementComplete(id, completed) {
|
||||
var listItem = qs('[data-id="' + id + '"]')
|
||||
|
||||
if (!listItem) {
|
||||
return
|
||||
}
|
||||
|
||||
listItem.className = completed ? 'completed' : ''
|
||||
|
||||
// In case it was toggled from an event and not by clicking the checkbox
|
||||
qs('input', listItem).checked = completed
|
||||
}
|
||||
|
||||
function _editItem(id, title) {
|
||||
var listItem = qs('[data-id="' + id + '"]')
|
||||
|
||||
if (!listItem) {
|
||||
return
|
||||
}
|
||||
|
||||
listItem.className = listItem.className + ' editing'
|
||||
|
||||
var input = document.createElement('input')
|
||||
input.className = 'edit'
|
||||
|
||||
listItem.appendChild(input)
|
||||
input.focus()
|
||||
input.value = title
|
||||
}
|
||||
|
||||
function _itemId(element) {
|
||||
var li = $parent(element, 'li')
|
||||
return parseInt(li.dataset.id, 10)
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user