bundlify everything

This commit is contained in:
Kent C. Dodds 2016-06-16 02:30:38 -06:00
parent 985e1562ef
commit 1307a2b85d
10 changed files with 854 additions and 870 deletions

View File

@ -39,13 +39,6 @@
<p>Ported to ES6 by <a href="https://twitter.com/kentcdodds">Kent C. Dodds</a></p> <p>Ported to ES6 by <a href="https://twitter.com/kentcdodds">Kent C. Dodds</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p> <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer> </footer>
<script src="src/helpers.js"></script>
<script src="src/store.js"></script>
<script src="src/model.js"></script>
<script src="src/template.js"></script>
<script src="src/view.js"></script>
<script src="src/controller.js"></script>
<script src="src/app.js"></script>
<script src="dist/bundle.js"></script> <script src="dist/bundle.js"></script>
</body> </body>
</html> </html>

View File

@ -1,28 +1,32 @@
/* global app, log */ /* global app, log */
(function(window) { 'use strict'
'use strict'
/** require('./view')
* Sets up a brand new Todo list. require('./helpers')
* require('./controller')
* @param {string} name The name of your new to do list. require('./model')
*/ require('./store')
function Todo(name) { require('./template')
/**
* Sets up a brand new Todo list.
*
* @param {string} name The name of your new to do list.
*/
function Todo(name) {
this.storage = new app.Store(name) this.storage = new app.Store(name)
this.model = new app.Model(this.storage) this.model = new app.Model(this.storage)
this.template = new app.Template() this.template = new app.Template()
this.view = new app.View(this.template) this.view = new app.View(this.template)
this.controller = new app.Controller(this.model, this.view) this.controller = new app.Controller(this.model, this.view)
} }
function onLoad() { function onLoad() {
var todo = new Todo('todos-vanillajs') var todo = new Todo('todos-vanillajs')
todo.controller.setView(document.location.hash) todo.controller.setView(document.location.hash)
log('view set') log('view set')
} }
// Export to window
// Export to window window.app = window.app || {}
window.app = window.app || {} window.app.onLoad = onLoad
window.app.onLoad = onLoad
})(window)

11
src/bootstrap.js vendored
View File

@ -1,7 +1,8 @@
/* global app, $on */ /* global app, $on */
(function(window) { 'use strict'
'use strict'
$on(window, 'load', app.onLoad) require('./app')
$on(window, 'hashchange', app.onLoad) require('./helpers')
})(window)
$on(window, 'load', app.onLoad)
$on(window, 'hashchange', app.onLoad)

View File

@ -1,14 +1,13 @@
(function(window) { 'use strict'
'use strict'
/** /**
* Takes a model and view and acts as the controller between them * Takes a model and view and acts as the controller between them
* *
* @constructor * @constructor
* @param {object} model The model instance * @param {object} model The model instance
* @param {object} view The view instance * @param {object} view The view instance
*/ */
function Controller(model, view) { function Controller(model, view) {
var that = this var that = this
that.model = model that.model = model
that.view = view that.view = view
@ -44,55 +43,55 @@
that.view.bind('toggleAll', function(status) { that.view.bind('toggleAll', function(status) {
that.toggleAll(status.completed) that.toggleAll(status.completed)
}) })
} }
/** /**
* Loads and initialises the view * Loads and initialises the view
* *
* @param {string} '' | 'active' | 'completed' * @param {string} '' | 'active' | 'completed'
*/ */
Controller.prototype.setView = function(locationHash) { Controller.prototype.setView = function(locationHash) {
var route = locationHash.split('/')[1] var route = locationHash.split('/')[1]
var page = route || '' var page = route || ''
this._updateFilterState(page) this._updateFilterState(page)
} }
/** /**
* An event to fire on load. Will get all items and display them in the * An event to fire on load. Will get all items and display them in the
* todo-list * todo-list
*/ */
Controller.prototype.showAll = function() { Controller.prototype.showAll = function() {
var that = this var that = this
that.model.read(function(data) { that.model.read(function(data) {
that.view.render('showEntries', data) that.view.render('showEntries', data)
}) })
} }
/** /**
* Renders all active tasks * Renders all active tasks
*/ */
Controller.prototype.showActive = function() { Controller.prototype.showActive = function() {
var that = this var that = this
that.model.read({completed: false}, function(data) { that.model.read({completed: false}, function(data) {
that.view.render('showEntries', data) that.view.render('showEntries', data)
}) })
} }
/** /**
* Renders all completed tasks * Renders all completed tasks
*/ */
Controller.prototype.showCompleted = function() { Controller.prototype.showCompleted = function() {
var that = this var that = this
that.model.read({completed: true}, function(data) { that.model.read({completed: true}, function(data) {
that.view.render('showEntries', data) that.view.render('showEntries', data)
}) })
} }
/** /**
* An event to fire whenever you want to add an item. Simply pass in the event * An event to fire whenever you want to add an item. Simply pass in the event
* object and it'll handle the DOM insertion and saving of the new item. * object and it'll handle the DOM insertion and saving of the new item.
*/ */
Controller.prototype.addItem = function(title) { Controller.prototype.addItem = function(title) {
var that = this var that = this
if (title.trim() === '') { if (title.trim() === '') {
@ -103,22 +102,22 @@
that.view.render('clearNewTodo') that.view.render('clearNewTodo')
that._filter(true) that._filter(true)
}) })
} }
/* /*
* Triggers the item editing mode. * Triggers the item editing mode.
*/ */
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: id, title: data[0].title})
}) })
} }
/* /*
* Finishes the item editing mode successfully. * Finishes the item editing mode successfully.
*/ */
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: title}, function() {
@ -127,38 +126,38 @@
} else { } else {
that.removeItem(id) that.removeItem(id)
} }
} }
/* /*
* Cancels the item editing mode. * Cancels the item editing mode.
*/ */
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: id, title: data[0].title})
}) })
} }
/** /**
* By giving it an ID it'll find the DOM element matching that ID, * By giving it an ID it'll find the DOM element matching that ID,
* remove it from the DOM and also remove it from storage. * remove it from the DOM and also remove it from storage.
* *
* @param {number} id The ID of the item to remove from the DOM and * @param {number} id The ID of the item to remove from the DOM and
* storage * storage
*/ */
Controller.prototype.removeItem = function(id) { Controller.prototype.removeItem = function(id) {
var that = this var that = this
that.model.remove(id, function() { that.model.remove(id, function() {
that.view.render('removeItem', id) that.view.render('removeItem', id)
}) })
that._filter() that._filter()
} }
/** /**
* Will remove all completed items from the DOM and storage. * Will remove all completed items from the DOM and storage.
*/ */
Controller.prototype.removeCompletedItems = function() { Controller.prototype.removeCompletedItems = function() {
var that = this var that = this
that.model.read({completed: true}, function(data) { that.model.read({completed: true}, function(data) {
data.forEach(function(item) { data.forEach(function(item) {
@ -167,18 +166,18 @@
}) })
that._filter() that._filter()
} }
/** /**
* Give it an ID of a model and a checkbox and it will update the item * Give it an ID of a model and a checkbox and it will update the item
* in storage based on the checkbox's state. * in storage based on the checkbox's state.
* *
* @param {number} id The ID of the element to complete or uncomplete * @param {number} id The ID of the element to complete or uncomplete
* @param {object} checkbox The checkbox to check the state of complete * @param {object} checkbox The checkbox to check the state of complete
* or not * or not
* @param {boolean|undefined} silent Prevent re-filtering the todo items * @param {boolean|undefined} silent Prevent re-filtering the todo items
*/ */
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: completed}, function() {
that.view.render('elementComplete', { that.view.render('elementComplete', {
@ -190,13 +189,13 @@
if (!silent) { if (!silent) {
that._filter() that._filter()
} }
} }
/** /**
* Will toggle ALL checkboxes' on/off state and completeness of models. * Will toggle ALL checkboxes' on/off state and completeness of models.
* Just pass in the event object. * Just pass in the event object.
*/ */
Controller.prototype.toggleAll = function(completed) { Controller.prototype.toggleAll = function(completed) {
var that = this var that = this
that.model.read({completed: !completed}, function(data) { that.model.read({completed: !completed}, function(data) {
data.forEach(function(item) { data.forEach(function(item) {
@ -205,13 +204,13 @@
}) })
that._filter() that._filter()
} }
/** /**
* Updates the pieces of the page which change depending on the remaining * Updates the pieces of the page which change depending on the remaining
* number of todos. * number of todos.
*/ */
Controller.prototype._updateCount = function() { Controller.prototype._updateCount = function() {
var that = this var that = this
that.model.getCount(function(todos) { that.model.getCount(function(todos) {
that.view.render('updateElementCount', todos.active) that.view.render('updateElementCount', todos.active)
@ -223,13 +222,13 @@
that.view.render('toggleAll', {checked: todos.completed === todos.total}) that.view.render('toggleAll', {checked: todos.completed === todos.total})
that.view.render('contentBlockVisibility', {visible: todos.total > 0}) that.view.render('contentBlockVisibility', {visible: todos.total > 0})
}) })
} }
/** /**
* Re-filters the todo items, based on the active route. * Re-filters the todo items, based on the active route.
* @param {boolean|undefined} force forces a re-painting of todo items. * @param {boolean|undefined} force forces a re-painting of todo items.
*/ */
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
@ -243,12 +242,12 @@
} }
this._lastActiveRoute = activeRoute this._lastActiveRoute = activeRoute
} }
/** /**
* Simply updates the filter nav's selected states * Simply updates the filter nav's selected states
*/ */
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.
this._activeRoute = currentPage this._activeRoute = currentPage
@ -260,9 +259,8 @@
this._filter() this._filter()
this.view.render('setFilter', currentPage) this.view.render('setFilter', currentPage)
} }
// Export to window // Export to window
window.app = window.app || {} window.app = window.app || {}
window.app.Controller = Controller window.app.Controller = Controller
})(window)

View File

@ -1,31 +1,28 @@
/*global NodeList */ 'use strict'
(function(window) {
'use strict'
// Get element(s) by CSS selector: // Get element(s) by CSS selector:
window.qs = function(selector, scope) { window.qs = function(selector, scope) {
return (scope || document).querySelector(selector) return (scope || document).querySelector(selector)
} }
window.qsa = function(selector, scope) { window.qsa = function(selector, scope) {
return (scope || document).querySelectorAll(selector) return (scope || document).querySelectorAll(selector)
} }
window.log = function log() {
window.log = function log() {
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.apply(window.console, arguments) // eslint-disable-line
} }
} }
// addEventListener wrapper: // addEventListener wrapper:
window.$on = function(target, type, callback, useCapture) { window.$on = function(target, type, callback, useCapture) {
target.addEventListener(type, callback, !!useCapture) target.addEventListener(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
window.$delegate = function(target, selector, type, handler) { window.$delegate = function(target, selector, type, handler) {
function dispatchEvent(event) { function dispatchEvent(event) {
var targetElement = event.target var targetElement = event.target
var potentialElements = window.qsa(selector, target) var potentialElements = window.qsa(selector, target)
@ -40,11 +37,11 @@
var useCapture = type === 'blur' || type === 'focus' var useCapture = type === 'blur' || type === 'focus'
window.$on(target, type, dispatchEvent, useCapture) window.$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');
window.$parent = function(element, tagName) { window.$parent = function(element, tagName) {
if (!element.parentNode) { if (!element.parentNode) {
return return
} }
@ -52,31 +49,30 @@
return element.parentNode return element.parentNode
} }
return window.$parent(element.parentNode, tagName) return window.$parent(element.parentNode, tagName)
} }
// removes an element from an array // removes an element from an array
// const x = [1,2,3] // const x = [1,2,3]
// remove(x, 2) // remove(x, 2)
// x ~== [1,3] // x ~== [1,3]
window.remove = function remove(array, thing) { window.remove = function remove(array, thing) {
const index = array.indexOf(thing) const index = array.indexOf(thing)
if (index === -1) { if (index === -1) {
return array return array
} }
array.splice(index, 1) array.splice(index, 1)
} }
// pad the left of the given string by the given size with the given character // pad the left of the given string by the given size with the given character
// leftPad('10', 3, '0') -> 010 // leftPad('10', 3, '0') -> 010
window.leftPad = function leftPad(str, size, padWith) { window.leftPad = function leftPad(str, size, padWith) {
if (size <= str.length) { if (size <= str.length) {
return str return str
} else { } else {
return Array(size - str.length + 1).join(padWith || '0') + str 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
})(window)

View File

@ -1,23 +1,22 @@
(function(window) { 'use strict'
'use strict'
/** /**
* Creates a new Model instance and hooks up the storage. * Creates a new Model instance and hooks up the storage.
* *
* @constructor * @constructor
* @param {object} storage A reference to the client side storage class * @param {object} storage A reference to the client side storage class
*/ */
function Model(storage) { function Model(storage) {
this.storage = storage this.storage = storage
} }
/** /**
* Creates a new todo model * Creates a new todo model
* *
* @param {string} [title] The title of the task * @param {string} [title] The title of the task
* @param {function} [callback] The callback to fire after the model is created * @param {function} [callback] The callback to fire after the model is created
*/ */
Model.prototype.create = function(title, callback) { Model.prototype.create = function(title, callback) {
title = title || '' title = title || ''
callback = callback || function() { callback = callback || function() {
} }
@ -28,24 +27,24 @@
} }
this.storage.save(newItem, callback) this.storage.save(newItem, 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() {
} }
@ -59,43 +58,43 @@
} else { } else {
this.storage.find(query, callback) this.storage.find(query, callback)
} }
} }
/** /**
* Updates a model by giving it an ID, data to update, and a callback to fire when * Updates a model by giving it an ID, data to update, and a callback to fire when
* the update is complete. * the update is complete.
* *
* @param {number} id The id of the model to update * @param {number} id The id of the model to update
* @param {object} data The properties to update and their new value * @param {object} data The properties to update and their new value
* @param {function} callback The callback to fire when the update is complete. * @param {function} callback The callback to fire when the update is complete.
*/ */
Model.prototype.update = function(id, data, callback) { Model.prototype.update = function(id, data, callback) {
this.storage.save(data, callback, id) this.storage.save(data, callback, id)
} }
/** /**
* Removes a model from storage * Removes a model from storage
* *
* @param {number} id The ID of the model to remove * @param {number} id The ID of the model to remove
* @param {function} callback The callback to fire when the removal is complete. * @param {function} callback The callback to fire when the removal is complete.
*/ */
Model.prototype.remove = function(id, callback) { Model.prototype.remove = function(id, callback) {
this.storage.remove(id, callback) this.storage.remove(id, callback)
} }
/** /**
* WARNING: Will remove ALL data from storage. * WARNING: Will remove ALL data from storage.
* *
* @param {function} callback The callback to fire when the storage is wiped. * @param {function} callback The callback to fire when the storage is wiped.
*/ */
Model.prototype.removeAll = function(callback) { Model.prototype.removeAll = function(callback) {
this.storage.drop(callback) this.storage.drop(callback)
} }
/** /**
* Returns a count of all todos * Returns a count of all todos
*/ */
Model.prototype.getCount = function(callback) { Model.prototype.getCount = function(callback) {
var todos = { var todos = {
active: 0, active: 0,
completed: 0, completed: 0,
@ -114,9 +113,8 @@
}) })
callback(todos) callback(todos)
}) })
} }
// Export to window // Export to window
window.app = window.app || {} window.app = window.app || {}
window.app.Model = Model window.app.Model = Model
})(window)

View File

@ -1,15 +1,14 @@
(function(window) { 'use strict'
'use strict'
/** /**
* 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,22 +23,22 @@
} }
callback.call(this, JSON.parse(localStorage[name])) callback.call(this, JSON.parse(localStorage[name]))
} }
/** /**
* Finds items based on a query given as a JS object * Finds items based on a query given as a JS object
* *
* @param {object} query The query to match against (i.e. {foo: 'bar'}) * @param {object} query The query to match against (i.e. {foo: 'bar'})
* @param {function} callback The callback to fire when the query has * @param {function} callback The callback to fire when the query has
* completed running * completed running
* *
* @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) {
if (!callback) { if (!callback) {
return return
} }
@ -54,28 +53,28 @@
} }
return true return true
})) }))
} }
/** /**
* Will retrieve all data from the collection * Will retrieve all data from the collection
* *
* @param {function} callback The callback to fire upon retrieving data * @param {function} callback The callback to fire upon retrieving data
*/ */
Store.prototype.findAll = function(callback) { Store.prototype.findAll = function(callback) {
callback = callback || function() { callback = callback || function() {
} }
callback.call(this, JSON.parse(localStorage[this._dbName]).todos) callback.call(this, JSON.parse(localStorage[this._dbName]).todos)
} }
/** /**
* Will save the given data to the DB. If no item exists it will create a new * Will save the given data to the DB. If no item exists it will create a new
* item, otherwise it'll simply update an existing item's properties * item, otherwise it'll simply update an existing item's properties
* *
* @param {object} updateData The data to save back into the DB * @param {object} updateData The data to save back into the DB
* @param {function} callback The callback to fire after saving * @param {function} callback The callback to fire after saving
* @param {number} id An optional param to enter an ID of an item to update * @param {number} id An optional param to enter an ID of an item to update
*/ */
Store.prototype.save = function(updateData, callback, id) { Store.prototype.save = function(updateData, callback, id) {
var data = JSON.parse(localStorage[this._dbName]) var data = JSON.parse(localStorage[this._dbName])
var todos = data.todos var todos = data.todos
@ -105,15 +104,15 @@
localStorage[this._dbName] = JSON.stringify(data) localStorage[this._dbName] = JSON.stringify(data)
callback.call(this, [updateData]) callback.call(this, [updateData])
} }
} }
/** /**
* Will remove an item from the Store based on its ID * Will remove an item from the Store based on its ID
* *
* @param {number} id The ID of the item you want to remove * @param {number} id The ID of the item you want to remove
* @param {function} callback The callback to fire after saving * @param {function} callback The callback to fire after saving
*/ */
Store.prototype.remove = function(id, callback) { Store.prototype.remove = function(id, callback) {
var data = JSON.parse(localStorage[this._dbName]) var data = JSON.parse(localStorage[this._dbName])
var todos = data.todos var todos = data.todos
@ -126,19 +125,18 @@
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)
} }
/** /**
* Will drop all storage and start fresh * Will drop all storage and start fresh
* *
* @param {function} callback The callback to fire after dropping the data * @param {function} callback The callback to fire after dropping the data
*/ */
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)
} }
// Export to window // Export to window
window.app = window.app || {} window.app = window.app || {}
window.app.Store = Store window.app.Store = Store
})(window)

View File

@ -1,34 +1,33 @@
(function(window) { 'use strict'
'use strict'
var htmlEscapes = { var htmlEscapes = {
'&': '&amp;', '&': '&amp;',
'<': '&lt;', '<': '&lt;',
'>': '&gt;', '>': '&gt;',
'"': '&quot;', '"': '&quot;',
'\'': '&#x27;', '\'': '&#x27;',
'`': '&#x60;' '`': '&#x60;'
} }
var escapeHtmlChar = function(chr) { var escapeHtmlChar = function(chr) {
return htmlEscapes[chr] return htmlEscapes[chr]
} }
var reUnescapedHtml = /[&<>"'`]/g 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)) ? return (string && reHasUnescapedHtml.test(string)) ?
string.replace(reUnescapedHtml, escapeHtmlChar) : string.replace(reUnescapedHtml, escapeHtmlChar) :
string string
} }
/** /**
* Sets up defaults for all the Template methods such as a default template * Sets up defaults for all the Template methods such as a default template
* *
* @constructor * @constructor
*/ */
function Template() { function Template() {
this.defaultTemplate = '<li data-id="{{id}}" class="{{completed}}">' + this.defaultTemplate = '<li data-id="{{id}}" class="{{completed}}">' +
'<div class="view">' + '<div class="view">' +
'<input class="toggle" type="checkbox" {{checked}}>' + '<input class="toggle" type="checkbox" {{checked}}>' +
@ -36,26 +35,26 @@
'<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 = ''
@ -78,35 +77,34 @@
} }
return view return view
} }
/** /**
* 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'
return '<strong>' + activeTodos + '</strong> item' + plural + ' left' return '<strong>' + activeTodos + '</strong> item' + plural + ' left'
} }
/** /**
* 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'
} else { } else {
return '' return ''
} }
} }
// Export to window // Export to window
window.app = window.app || {} window.app = window.app || {}
window.app.Template = Template window.app.Template = Template
})(window)

View File

@ -1,19 +1,17 @@
/*global qs, qsa, $on, $parent, $delegate */ /*global qs, qsa, $on, $parent, $delegate */
/* eslint no-invalid-this: 0 */ /* eslint no-invalid-this: 0 */
'use strict'
(function(window) { /**
'use strict' * View that abstracts away the browser's DOM completely.
* It has two simple entry points:
/** *
* View that abstracts away the browser's DOM completely. * - bind(eventName, handler)
* It has two simple entry points: * Takes a todo application event and registers the handler
* * - render(command, parameterObject)
* - bind(eventName, handler) * Renders the given command with the options
* Takes a todo application event and registers the handler */
* - render(command, parameterObject) function View(template) {
* Renders the given command with the options
*/
function View(template) {
this.template = template this.template = template
this.ENTER_KEY = 13 this.ENTER_KEY = 13
@ -26,27 +24,27 @@
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) { 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)
} }
} }
View.prototype._clearCompletedButton = function(completedCount, visible) { View.prototype._clearCompletedButton = function(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) { 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'
} }
View.prototype._elementComplete = function(id, completed) { View.prototype._elementComplete = function(id, completed) {
var listItem = qs('[data-id="' + id + '"]') var listItem = qs('[data-id="' + id + '"]')
if (!listItem) { if (!listItem) {
@ -57,9 +55,9 @@
// In case it was toggled from an event and not by clicking the checkbox // In case it was toggled from an event and not by clicking the checkbox
qs('input', listItem).checked = completed qs('input', listItem).checked = completed
} }
View.prototype._editItem = function(id, title) { View.prototype._editItem = function(id, title) {
var listItem = qs('[data-id="' + id + '"]') var listItem = qs('[data-id="' + id + '"]')
if (!listItem) { if (!listItem) {
@ -74,9 +72,9 @@
listItem.appendChild(input) listItem.appendChild(input)
input.focus() input.focus()
input.value = title input.value = title
} }
View.prototype._editItemDone = function(id, title) { View.prototype._editItemDone = function(id, title) {
var listItem = qs('[data-id="' + id + '"]') var listItem = qs('[data-id="' + id + '"]')
if (!listItem) { if (!listItem) {
@ -91,9 +89,9 @@
qsa('label', listItem).forEach(function(label) { qsa('label', listItem).forEach(function(label) {
label.textContent = title label.textContent = title
}) })
} }
View.prototype.render = function(viewCmd, parameter) { View.prototype.render = function(viewCmd, parameter) {
var that = this var that = this
var viewCommands = { var viewCommands = {
showEntries: function() { showEntries: function() {
@ -132,14 +130,14 @@
} }
viewCommands[viewCmd]() viewCommands[viewCmd]()
} }
View.prototype._itemId = function(element) { 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) { 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) {
@ -157,9 +155,9 @@
this.blur() this.blur()
} }
}) })
} }
View.prototype._bindItemEditCancel = function(handler) { View.prototype._bindItemEditCancel = function(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) {
@ -169,9 +167,9 @@
handler({id: that._itemId(this)}) handler({id: that._itemId(this)})
} }
}) })
} }
View.prototype.bind = function(event, handler) { // eslint-disable-line View.prototype.bind = function(event, handler) { // eslint-disable-line
var that = this var that = this
if (event === 'newTodo') { if (event === 'newTodo') {
$on(that.$newTodo, 'change', function() { $on(that.$newTodo, 'change', function() {
@ -212,9 +210,8 @@
} else if (event === 'itemEditCancel') { } else if (event === 'itemEditCancel') {
that._bindItemEditCancel(handler) that._bindItemEditCancel(handler)
} }
} }
// Export to window // Export to window
window.app = window.app || {} window.app = window.app || {}
window.app.View = View window.app.View = View
})(window)

View File

@ -4,7 +4,7 @@ const webpackValidator = require('webpack-validator')
const {getIfUtils} = require('webpack-config-utils') const {getIfUtils} = require('webpack-config-utils')
module.exports = env => { module.exports = env => {
const {ifProd} = getIfUtils(env) const {ifProd, ifNotProd} = getIfUtils(env)
const config = webpackValidator({ const config = webpackValidator({
context: resolve('src'), context: resolve('src'),
entry: './bootstrap.js', entry: './bootstrap.js',
@ -12,6 +12,7 @@ module.exports = env => {
filename: 'bundle.js', filename: 'bundle.js',
path: resolve('dist'), path: resolve('dist'),
publicPath: '/dist/', publicPath: '/dist/',
pathinfo: ifNotProd(),
}, },
devtool: ifProd('source-map', 'eval'), devtool: ifProd('source-map', 'eval'),
}) })