👾 closures closures closures!

This commit is contained in:
Kent C. Dodds 2015-08-10 06:51:53 -06:00
parent 9c01a555b1
commit 3d0ac2f76c
7 changed files with 792 additions and 807 deletions

View File

@ -1,4 +1,5 @@
/*global app, $on */
'use strict';
require('todomvc-common/base.css');
require('todomvc-app-css/index.css');
require('./view');
@ -7,31 +8,27 @@ require('./controller');
require('./model');
require('./store');
require('./template');
(function () {
'use strict';
/**
/**
* Sets up a brand new Todo list.
*
* @param {string} name The name of your new to do list.
*/
function Todo(name) {
function Todo(name) {
this.storage = new app.Store(name);
this.model = new app.Model(this.storage);
this.template = new app.Template();
this.view = new app.View(this.template);
this.controller = new app.Controller(this.model, this.view);
}
}
var todo;
var todo;
function setView() {
function setView() {
todo.controller.setView(document.location.hash);
}
}
$on(window, 'load', function() {
$on(window, 'load', function () {
todo = new Todo('todos-vanillajs');
setView();
});
$on(window, 'hashchange', setView);
})();
});
$on(window, 'hashchange', setView);

View File

@ -1,14 +1,12 @@
(function (window) {
'use strict';
/**
'use strict';
/**
* Takes a model and view and acts as the controller between them
*
* @constructor
* @param {object} model The model instance
* @param {object} view The view instance
*/
function Controller(model, view) {
function Controller(model, view) {
var that = this;
that.model = model;
that.view = view;
@ -44,55 +42,55 @@
that.view.bind('toggleAll', function (status) {
that.toggleAll(status.completed);
});
}
}
/**
/**
* Loads and initialises the view
*
* @param {string} '' | 'active' | 'completed'
*/
Controller.prototype.setView = function (locationHash) {
Controller.prototype.setView = function (locationHash) {
var route = locationHash.split('/')[1];
var page = route || '';
this._updateFilterState(page);
};
};
/**
/**
* An event to fire on load. Will get all items and display them in the
* todo-list
*/
Controller.prototype.showAll = function () {
Controller.prototype.showAll = function () {
var that = this;
that.model.read(function (data) {
that.view.render('showEntries', data);
});
};
};
/**
/**
* Renders all active tasks
*/
Controller.prototype.showActive = function () {
Controller.prototype.showActive = function () {
var that = this;
that.model.read({ completed: false }, function (data) {
that.model.read({completed: false}, function (data) {
that.view.render('showEntries', data);
});
};
};
/**
/**
* Renders all completed tasks
*/
Controller.prototype.showCompleted = function () {
Controller.prototype.showCompleted = function () {
var that = this;
that.model.read({ completed: true }, function (data) {
that.model.read({completed: true}, function (data) {
that.view.render('showEntries', data);
});
};
};
/**
/**
* 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.
*/
Controller.prototype.addItem = function (title) {
Controller.prototype.addItem = function (title) {
var that = this;
if (title.trim() === '') {
@ -103,22 +101,22 @@
that.view.render('clearNewTodo');
that._filter(true);
});
};
};
/*
/*
* Triggers the item editing mode.
*/
Controller.prototype.editItem = function (id) {
Controller.prototype.editItem = function (id) {
var that = this;
that.model.read(id, function (data) {
that.view.render('editItem', {id: id, title: data[0].title});
});
};
};
/*
/*
* Finishes the item editing mode successfully.
*/
Controller.prototype.editItemSave = function (id, title) {
Controller.prototype.editItemSave = function (id, title) {
var that = this;
if (title.trim()) {
that.model.update(id, {title: title}, function () {
@ -127,49 +125,49 @@
} else {
that.removeItem(id);
}
};
};
/*
/*
* Cancels the item editing mode.
*/
Controller.prototype.editItemCancel = function (id) {
Controller.prototype.editItemCancel = function (id) {
var that = this;
that.model.read(id, function (data) {
that.view.render('editItemDone', {id: id, title: data[0].title});
});
};
};
/**
/**
* 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.
*
* @param {number} id The ID of the item to remove from the DOM and
* storage
*/
Controller.prototype.removeItem = function (id) {
Controller.prototype.removeItem = function (id) {
var that = this;
that.model.remove(id, function () {
that.view.render('removeItem', id);
});
that._filter();
};
};
/**
/**
* Will remove all completed items from the DOM and storage.
*/
Controller.prototype.removeCompletedItems = function () {
Controller.prototype.removeCompletedItems = function () {
var that = this;
that.model.read({ completed: true }, function (data) {
that.model.read({completed: true}, function (data) {
data.forEach(function (item) {
that.removeItem(item.id);
});
});
that._filter();
};
};
/**
/**
* Give it an ID of a model and a checkbox and it will update the item
* in storage based on the checkbox's state.
*
@ -178,9 +176,9 @@
* or not
* @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;
that.model.update(id, { completed: completed }, function () {
that.model.update(id, {completed: completed}, function () {
that.view.render('elementComplete', {
id: id,
completed: completed
@ -190,28 +188,28 @@
if (!silent) {
that._filter();
}
};
};
/**
/**
* Will toggle ALL checkboxes' on/off state and completeness of models.
* Just pass in the event object.
*/
Controller.prototype.toggleAll = function (completed) {
Controller.prototype.toggleAll = function (completed) {
var that = this;
that.model.read({ completed: !completed }, function (data) {
that.model.read({completed: !completed}, function (data) {
data.forEach(function (item) {
that.toggleComplete(item.id, completed, true);
});
});
that._filter();
};
};
/**
/**
* Updates the pieces of the page which change depending on the remaining
* number of todos.
*/
Controller.prototype._updateCount = function () {
Controller.prototype._updateCount = function () {
var that = this;
that.model.getCount(function (todos) {
that.view.render('updateElementCount', todos.active);
@ -223,13 +221,13 @@
that.view.render('toggleAll', {checked: todos.completed === todos.total});
that.view.render('contentBlockVisibility', {visible: todos.total > 0});
});
};
};
/**
/**
* Re-filters the todo items, based on the active route.
* @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);
// Update the elements on the page, which change with each completed todo
@ -243,12 +241,12 @@
}
this._lastActiveRoute = activeRoute;
};
};
/**
/**
* 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
// items as they are marked complete or incomplete.
this._activeRoute = currentPage;
@ -260,9 +258,8 @@
this._filter();
this.view.render('setFilter', currentPage);
};
};
// Export to window
window.app = window.app || {};
window.app.Controller = Controller;
})(window);
// Export to window
window.app = window.app || {};
window.app.Controller = Controller;

View File

@ -1,23 +1,21 @@
/*global NodeList */
(function (window) {
'use strict';
// Get element(s) by CSS selector:
window.qs = function (selector, scope) {
'use strict';
// Get element(s) by CSS selector:
window.qs = function (selector, scope) {
return (scope || document).querySelector(selector);
};
window.qsa = function (selector, scope) {
};
window.qsa = function (selector, scope) {
return (scope || document).querySelectorAll(selector);
};
};
// addEventListener wrapper:
window.$on = function (target, type, callback, useCapture) {
// addEventListener wrapper:
window.$on = function (target, type, callback, useCapture) {
target.addEventListener(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
window.$delegate = function (target, selector, type, handler) {
// Attach a handler to event for all elements that match the selector,
// now or in the future, based on a root element
window.$delegate = function (target, selector, type, handler) {
function dispatchEvent(event) {
var targetElement = event.target;
var potentialElements = window.qsa(selector, target);
@ -32,11 +30,11 @@
var useCapture = type === 'blur' || type === 'focus';
window.$on(target, type, dispatchEvent, useCapture);
};
};
// Find the element's parent with the given tag name:
// $parent(qs('a'), 'div');
window.$parent = function (element, tagName) {
// Find the element's parent with the given tag name:
// $parent(qs('a'), 'div');
window.$parent = function (element, tagName) {
if (!element.parentNode) {
return;
}
@ -44,9 +42,8 @@
return element.parentNode;
}
return window.$parent(element.parentNode, tagName);
};
};
// Allow for looping on nodes by chaining:
// qsa('.foo').forEach(function () {})
NodeList.prototype.forEach = Array.prototype.forEach;
})(window);
// Allow for looping on nodes by chaining:
// qsa('.foo').forEach(function () {})
NodeList.prototype.forEach = Array.prototype.forEach;

View File

@ -1,25 +1,24 @@
(function (window) {
'use strict';
/**
'use strict';
/**
* Creates a new Model instance and hooks up the storage.
*
* @constructor
* @param {object} storage A reference to the client side storage class
*/
function Model(storage) {
function Model(storage) {
this.storage = storage;
}
}
/**
/**
* Creates a new todo model
*
* @param {string} [title] The title of the task
* @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 || '';
callback = callback || function () {};
callback = callback || function () {
};
var newItem = {
title: title.trim(),
@ -27,9 +26,9 @@
};
this.storage.save(newItem, 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
@ -44,22 +43,23 @@
* //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;
callback = callback || function () {};
callback = callback || function () {
};
if (queryType === 'function') {
callback = query;
return this.storage.findAll(callback);
} else if (queryType === 'string' || queryType === 'number') {
query = parseInt(query, 10);
this.storage.find({ id: query }, callback);
this.storage.find({id: query}, callback);
} else {
this.storage.find(query, callback);
}
};
};
/**
/**
* Updates a model by giving it an ID, data to update, and a callback to fire when
* the update is complete.
*
@ -67,33 +67,33 @@
* @param {object} data The properties to update and their new value
* @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);
};
};
/**
/**
* Removes a model from storage
*
* @param {number} id The ID of the model to remove
* @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);
};
};
/**
/**
* WARNING: Will remove ALL data from storage.
*
* @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);
};
};
/**
/**
* Returns a count of all todos
*/
Model.prototype.getCount = function (callback) {
Model.prototype.getCount = function (callback) {
var todos = {
active: 0,
completed: 0,
@ -112,9 +112,8 @@
});
callback(todos);
});
};
};
// Export to window
window.app = window.app || {};
window.app.Model = Model;
})(window);
// Export to window
window.app = window.app || {};
window.app.Model = Model;

View File

@ -1,8 +1,6 @@
/*jshint eqeqeq:false */
(function (window) {
'use strict';
/**
'use strict';
/**
* Creates a new client side storage object and will create an empty
* collection if no collection already exists.
*
@ -10,8 +8,9 @@
* @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 () {};
function Store(name, callback) {
callback = callback || function () {
};
this._dbName = name;
@ -24,9 +23,9 @@
}
callback.call(this, JSON.parse(localStorage[name]));
}
}
/**
/**
* Finds items based on a query given as a JS object
*
* @param {object} query The query to match against (i.e. {foo: 'bar'})
@ -39,7 +38,7 @@
* // hello: world in their properties
* });
*/
Store.prototype.find = function (query, callback) {
Store.prototype.find = function (query, callback) {
if (!callback) {
return;
}
@ -54,19 +53,20 @@
}
return true;
}));
};
};
/**
/**
* Will retrieve all data from the collection
*
* @param {function} callback The callback to fire upon retrieving data
*/
Store.prototype.findAll = function (callback) {
callback = callback || function () {};
callback.call(this, JSON.parse(localStorage[this._dbName]).todos);
Store.prototype.findAll = function (callback) {
callback = callback || function () {
};
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
* item, otherwise it'll simply update an existing item's properties
*
@ -74,11 +74,12 @@
* @param {function} callback The callback to fire after saving
* @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 todos = data.todos;
callback = callback || function () {};
callback = callback || function () {
};
// If an ID was actually given, find the item and update each property
if (id) {
@ -101,15 +102,15 @@
localStorage[this._dbName] = JSON.stringify(data);
callback.call(this, [updateData]);
}
};
};
/**
/**
* Will remove an item from the Store based on its ID
*
* @param {number} id The ID of the item you want to remove
* @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 todos = data.todos;
@ -122,19 +123,18 @@
localStorage[this._dbName] = JSON.stringify(data);
callback.call(this, JSON.parse(localStorage[this._dbName]).todos);
};
};
/**
/**
* Will drop all storage and start fresh
*
* @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: []});
callback.call(this, JSON.parse(localStorage[this._dbName]).todos);
};
};
// Export to window
window.app = window.app || {};
window.app.Store = Store;
})(window);
// Export to window
window.app = window.app || {};
window.app.Store = Store;

View File

@ -1,35 +1,34 @@
/*jshint laxbreak:true */
(function (window) {
'use strict';
'use strict';
var htmlEscapes = {
var htmlEscapes = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
'\'': '&#x27;',
'`': '&#x60;'
};
};
var escapeHtmlChar = function (chr) {
var escapeHtmlChar = function (chr) {
return htmlEscapes[chr];
};
};
var reUnescapedHtml = /[&<>"'`]/g,
var reUnescapedHtml = /[&<>"'`]/g,
reHasUnescapedHtml = new RegExp(reUnescapedHtml.source);
var escape = function (string) {
var escape = function (string) {
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
};
};
/**
/**
* Sets up defaults for all the Template methods such as a default template
*
* @constructor
*/
function Template() {
function Template() {
this.defaultTemplate
= '<li data-id="{{id}}" class="{{completed}}">'
+ '<div class="view">'
@ -38,9 +37,9 @@
+ '<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
@ -57,7 +56,7 @@
* completed: 0,
* });
*/
Template.prototype.show = function (data) {
Template.prototype.show = function (data) {
var i, l;
var view = '';
@ -80,35 +79,34 @@
}
return view;
};
};
/**
/**
* 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) {
Template.prototype.itemCounter = function (activeTodos) {
var plural = activeTodos === 1 ? '' : 's';
return '<strong>' + activeTodos + '</strong> item' + plural + ' left';
};
};
/**
/**
* 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) {
Template.prototype.clearCompletedButton = function (completedTodos) {
if (completedTodos > 0) {
return 'Clear completed';
} else {
return '';
}
};
};
// Export to window
window.app = window.app || {};
window.app.Template = Template;
})(window);
// Export to window
window.app = window.app || {};
window.app.Template = Template;

View File

@ -1,9 +1,7 @@
/*global qs, qsa, $on, $parent, $delegate */
'use strict';
require('./helpers');
(function (window) {
'use strict';
/**
/**
* View that abstracts away the browser's DOM completely.
* It has two simple entry points:
*
@ -12,7 +10,7 @@ require('./helpers');
* - render(command, parameterObject)
* Renders the given command with the options
*/
function View(template) {
function View(template) {
this.template = template;
this.ENTER_KEY = 13;
@ -25,27 +23,27 @@ require('./helpers');
this.$footer = qs('.footer');
this.$toggleAll = qs('.toggle-all');
this.$newTodo = qs('.new-todo');
}
}
View.prototype._removeItem = function (id) {
View.prototype._removeItem = function (id) {
var elem = qs('[data-id="' + id + '"]');
if (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.style.display = visible ? 'block' : 'none';
};
};
View.prototype._setFilter = function (currentPage) {
View.prototype._setFilter = function (currentPage) {
qs('.filters .selected').className = '';
qs('.filters [href="#/' + currentPage + '"]').className = 'selected';
};
};
View.prototype._elementComplete = function (id, completed) {
View.prototype._elementComplete = function (id, completed) {
var listItem = qs('[data-id="' + id + '"]');
if (!listItem) {
@ -56,9 +54,9 @@ require('./helpers');
// 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) {
View.prototype._editItem = function (id, title) {
var listItem = qs('[data-id="' + id + '"]');
if (!listItem) {
@ -73,9 +71,9 @@ require('./helpers');
listItem.appendChild(input);
input.focus();
input.value = title;
};
};
View.prototype._editItemDone = function (id, title) {
View.prototype._editItemDone = function (id, title) {
var listItem = qs('[data-id="' + id + '"]');
if (!listItem) {
@ -90,9 +88,9 @@ require('./helpers');
qsa('label', listItem).forEach(function (label) {
label.textContent = title;
});
};
};
View.prototype.render = function (viewCmd, parameter) {
View.prototype.render = function (viewCmd, parameter) {
var that = this;
var viewCommands = {
showEntries: function () {
@ -131,14 +129,14 @@ require('./helpers');
};
viewCommands[viewCmd]();
};
};
View.prototype._itemId = function (element) {
View.prototype._itemId = function (element) {
var li = $parent(element, 'li');
return parseInt(li.dataset.id, 10);
};
};
View.prototype._bindItemEditDone = function (handler) {
View.prototype._bindItemEditDone = function (handler) {
var that = this;
$delegate(that.$todoList, 'li .edit', 'blur', function () {
if (!this.dataset.iscanceled) {
@ -156,9 +154,9 @@ require('./helpers');
this.blur();
}
});
};
};
View.prototype._bindItemEditCancel = function (handler) {
View.prototype._bindItemEditCancel = function (handler) {
var that = this;
$delegate(that.$todoList, 'li .edit', 'keyup', function (event) {
if (event.keyCode === that.ESCAPE_KEY) {
@ -168,9 +166,9 @@ require('./helpers');
handler({id: that._itemId(this)});
}
});
};
};
View.prototype.bind = function (event, handler) {
View.prototype.bind = function (event, handler) {
var that = this;
if (event === 'newTodo') {
$on(that.$newTodo, 'change', function () {
@ -211,9 +209,8 @@ require('./helpers');
} else if (event === 'itemEditCancel') {
that._bindItemEditCancel(handler);
}
};
};
// Export to window
window.app = window.app || {};
window.app.View = View;
}(window));
// Export to window
window.app = window.app || {};
window.app.View = View;