es6ify stuff

This commit is contained in:
Kent C. Dodds 2016-06-29 07:39:14 -06:00
parent 6bb1890932
commit b25fcb42ca
9 changed files with 275 additions and 280 deletions

View File

@ -1,17 +1,17 @@
require('todomvc-app-css/index.css') import 'todomvc-app-css/index.css'
var View = require('./view') import View from './view'
var helpers = require('./helpers') import {log} from './helpers'
var Controller = require('./controller') import Controller from './controller'
var Model = require('./model') import Model from './model'
var Store = require('./store') import Store from './store'
var Template = require('./template') import Template from './template'
/** /**
* Sets up a brand new Todo list. * Sets up a brand new Todo list.
* *
* @param {string} name The name of your new to do list. * @param {string} name The name of your new to do list.
*/ */
function Todo(name) { function Todo(name) {
this.storage = new Store(name) this.storage = new Store(name)
this.model = new Model(this.storage) this.model = new Model(this.storage)
@ -20,8 +20,8 @@ function Todo(name) {
this.controller = new Controller(this.model, this.view) this.controller = new Controller(this.model, this.view)
} }
module.exports.onLoad = function onLoad() { export function onLoad() { // eslint-disable-line import/prefer-default-export
var todo = new Todo('todos-vanillajs') const todo = new Todo('todos-vanillajs')
todo.controller.setView(document.location.hash) todo.controller.setView(document.location.hash)
helpers.log('view set') log('view set')
} }

10
src/bootstrap.js vendored
View File

@ -1,6 +1,6 @@
/* eslint no-console:0 */ /* eslint no-console:0 */
var app = require('./app') import {onLoad} from './app'
var helpers = require('./helpers') import {$on} from './helpers'
// this is only relevant when using `hot` mode with webpack // this is only relevant when using `hot` mode with webpack
// special thanks to Eric Clemmons: https://github.com/ericclemmons/webpack-hot-server-example // special thanks to Eric Clemmons: https://github.com/ericclemmons/webpack-hot-server-example
@ -11,7 +11,7 @@ if (module.hot) {
}) })
if (reloading) { if (reloading) {
console.log('🔁 HMR Reloading.') console.log('🔁 HMR Reloading.')
app.onLoad() onLoad()
} else { } else {
console.info('✅ HMR Enabled.') console.info('✅ HMR Enabled.')
bootstrap() bootstrap()
@ -22,6 +22,6 @@ if (module.hot) {
} }
function bootstrap() { function bootstrap() {
helpers.$on(window, 'load', app.onLoad) $on(window, 'load', onLoad)
helpers.$on(window, 'hashchange', app.onLoad) $on(window, 'hashchange', onLoad)
} }

View File

@ -1,4 +1,4 @@
module.exports = Controller export default 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: id, title: data[0].title}) that.view.render('editItem', {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: title}, function() { that.model.update(id, {title}, function() {
that.view.render('editItemDone', {id: id, title: title}) that.view.render('editItemDone', {id, 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: id, title: data[0].title}) that.view.render('editItemDone', {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: completed}, function() { that.model.update(id, {completed}, function() {
that.view.render('elementComplete', { that.view.render('elementComplete', {
id: id, id,
completed: completed completed,
}) })
}) })

View File

@ -1,4 +1,4 @@
var Controller = require('./controller') import Controller from './controller'
describe('controller', () => { describe('controller', () => {
it('exists', () => { it('exists', () => {

View File

@ -1,4 +1,4 @@
module.exports = {qs, qsa, log, $on, $delegate, $parent, remove, leftPad} export {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,9 +9,9 @@ function qsa(selector, scope) {
return (scope || document).querySelectorAll(selector) return (scope || document).querySelectorAll(selector)
} }
function log() { function log(...args) {
if (window.console && window.console.log) { if (window.console && window.console.log) {
window.console.log.apply(window.console, arguments) // eslint-disable-line window.console.log(...args)
} }
} }
@ -23,6 +23,10 @@ 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)
@ -32,18 +36,13 @@ 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 return undefined
} }
if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) { if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
return element.parentNode return element.parentNode

View File

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

View File

@ -1,13 +1,13 @@
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() {
} }
@ -85,11 +85,9 @@ 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) { for (var key in updateData) { // eslint-disable-line guard-for-in
if (updateData.hasOwnProperty(key)) {
todos[i][key] = updateData[key] todos[i][key] = updateData[key]
} }
}
break break
} }
} }
@ -117,7 +115,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) { // eslint-disable-line if (todos[i].id === id) {
todos.splice(i, 1) todos.splice(i, 1)
break break
} }

View File

@ -1,4 +1,4 @@
module.exports = Template export default Template
var htmlEscapes = { var htmlEscapes = {
'&': '&amp;', '&': '&amp;',
@ -17,9 +17,11 @@ var reUnescapedHtml = /[&<>"'`]/g
var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source) var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source)
var escape = function(string) { var escape = function(string) {
return (string && reHasUnescapedHtml.test(string)) ? if (string && reHasUnescapedHtml.test(string)) {
string.replace(reUnescapedHtml, escapeHtmlChar) : return string.replace(reUnescapedHtml, escapeHtmlChar)
string } else {
return string
}
} }
/** /**
@ -28,32 +30,34 @@ var escape = function(string) {
* @constructor * @constructor
*/ */
function Template() { function Template() {
this.defaultTemplate = '<li data-id="{{id}}" class="{{completed}}">' + this.defaultTemplate = `
'<div class="view">' + <li data-id="{{id}}" class="{{completed}}">
'<input class="toggle" type="checkbox" {{checked}}>' + <div class="view">
'<label>{{title}}</label>' + <input class="toggle" type="checkbox" {{checked}} />
'<button class="destroy"></button>' + <label>{{title}}</label>
'</div>' + <button class="destroy"></button>
'</li>' </div>
</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 = ''
@ -80,11 +84,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'
@ -92,11 +96,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,24 +1,17 @@
/* eslint no-invalid-this: 0 */ /* eslint no-invalid-this: 0, complexity:[2, 9] */
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
*/ */
function View(template) { export default class View {
constructor(template) {
this.template = template this.template = template
this.ENTER_KEY = 13 this.ENTER_KEY = 13
@ -31,57 +24,22 @@ function View(template) {
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')
} }
View.prototype._removeItem = function(id) { _removeItem(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)
} }
} }
View.prototype._clearCompletedButton = function(completedCount, visible) { _clearCompletedButton(completedCount, visible) {
this.$clearCompleted.innerHTML = this.template.clearCompletedButton(completedCount) this.$clearCompleted.innerHTML = this.template.clearCompletedButton(completedCount)
this.$clearCompleted.style.display = visible ? 'block' : 'none' 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
} }
listItem.className = completed ? 'completed' : '' _editItemDone(id, title) {
// 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 + '"]') var listItem = qs('[data-id="' + id + '"]')
if (!listItem) { if (!listItem) {
@ -96,9 +54,9 @@ View.prototype._editItemDone = function(id, title) {
qsa('label', listItem).forEach(function(label) { qsa('label', listItem).forEach(function(label) {
label.textContent = title label.textContent = title
}) })
} }
View.prototype.render = function(viewCmd, parameter) { render(viewCmd, parameter) {
var that = this var that = this
var viewCommands = { var viewCommands = {
showEntries: function() { showEntries: function() {
@ -120,16 +78,16 @@ View.prototype.render = function(viewCmd, parameter) {
that.$toggleAll.checked = parameter.checked that.$toggleAll.checked = parameter.checked
}, },
setFilter: function() { setFilter: function() {
that._setFilter(parameter) _setFilter(parameter)
}, },
clearNewTodo: function() { clearNewTodo: function() {
that.$newTodo.value = '' that.$newTodo.value = ''
}, },
elementComplete: function() { elementComplete: function() {
that._elementComplete(parameter.id, parameter.completed) _elementComplete(parameter.id, parameter.completed)
}, },
editItem: function() { editItem: function() {
that._editItem(parameter.id, parameter.title) _editItem(parameter.id, parameter.title)
}, },
editItemDone: function() { editItemDone: function() {
that._editItemDone(parameter.id, parameter.title) that._editItemDone(parameter.id, parameter.title)
@ -137,19 +95,14 @@ View.prototype.render = function(viewCmd, parameter) {
} }
viewCommands[viewCmd]() viewCommands[viewCmd]()
} }
View.prototype._itemId = function(element) { _bindItemEditDone(handler) {
var li = $parent(element, 'li')
return parseInt(li.dataset.id, 10)
}
View.prototype._bindItemEditDone = function(handler) {
var that = this var that = this
$delegate(that.$todoList, 'li .edit', 'blur', function() { $delegate(that.$todoList, 'li .edit', 'blur', function() {
if (!this.dataset.iscanceled) { if (!this.dataset.iscanceled) {
handler({ handler({
id: that._itemId(this), id: _itemId(this),
title: this.value title: this.value
}) })
} }
@ -162,21 +115,21 @@ View.prototype._bindItemEditDone = function(handler) {
this.blur() this.blur()
} }
}) })
} }
View.prototype._bindItemEditCancel = function(handler) { _bindItemEditCancel(handler) {
var that = this var that = this
$delegate(that.$todoList, 'li .edit', 'keyup', function(event) { $delegate(that.$todoList, 'li .edit', 'keyup', function(event) {
if (event.keyCode === that.ESCAPE_KEY) { if (event.keyCode === that.ESCAPE_KEY) {
this.dataset.iscanceled = true this.dataset.iscanceled = true
this.blur() this.blur()
handler({id: that._itemId(this)}) handler({id: _itemId(this)})
} }
}) })
} }
View.prototype.bind = function(event, handler) { // eslint-disable-line bind(event, handler) {
var that = this var that = this
if (event === 'newTodo') { if (event === 'newTodo') {
$on(that.$newTodo, 'change', function() { $on(that.$newTodo, 'change', function() {
@ -195,18 +148,18 @@ View.prototype.bind = function(event, handler) { // eslint-disable-line
} else if (event === 'itemEdit') { } else if (event === 'itemEdit') {
$delegate(that.$todoList, 'li label', 'dblclick', function() { $delegate(that.$todoList, 'li label', 'dblclick', function() {
handler({id: that._itemId(this)}) handler({id: _itemId(this)})
}) })
} else if (event === 'itemRemove') { } else if (event === 'itemRemove') {
$delegate(that.$todoList, '.destroy', 'click', function() { $delegate(that.$todoList, '.destroy', 'click', function() {
handler({id: that._itemId(this)}) handler({id: _itemId(this)})
}) })
} else if (event === 'itemToggle') { } else if (event === 'itemToggle') {
$delegate(that.$todoList, '.toggle', 'click', function() { $delegate(that.$todoList, '.toggle', 'click', function() {
handler({ handler({
id: that._itemId(this), id: _itemId(this),
completed: this.checked completed: this.checked
}) })
}) })
@ -217,4 +170,45 @@ View.prototype.bind = function(event, handler) { // eslint-disable-line
} else if (event === 'itemEditCancel') { } else if (event === 'itemEditCancel') {
that._bindItemEditCancel(handler) 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)
} }