👾 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 */ /*global app, $on */
'use strict';
require('todomvc-common/base.css'); require('todomvc-common/base.css');
require('todomvc-app-css/index.css'); require('todomvc-app-css/index.css');
require('./view'); require('./view');
@ -7,31 +8,27 @@ require('./controller');
require('./model'); require('./model');
require('./store'); require('./store');
require('./template'); 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) {
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;
* 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.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; function setView() {
todo.controller.setView(document.location.hash);
}
function setView() { $on(window, 'load', function () {
todo.controller.setView(document.location.hash); todo = new Todo('todos-vanillajs');
} setView();
});
$on(window, 'load', function() { $on(window, 'hashchange', setView);
todo = new Todo('todos-vanillajs');
setView();
});
$on(window, 'hashchange', setView);
})();

View File

@ -1,268 +1,265 @@
(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) {
var that = this;
that.model = model;
that.view = view;
/** that.view.bind('newTodo', function (title) {
* Takes a model and view and acts as the controller between them that.addItem(title);
* });
* @constructor
* @param {object} model The model instance
* @param {object} view The view instance
*/
function Controller(model, view) {
var that = this;
that.model = model;
that.view = view;
that.view.bind('newTodo', function (title) { that.view.bind('itemEdit', function (item) {
that.addItem(title); that.editItem(item.id);
}); });
that.view.bind('itemEdit', function (item) { that.view.bind('itemEditDone', function (item) {
that.editItem(item.id); that.editItemSave(item.id, item.title);
}); });
that.view.bind('itemEditDone', function (item) { that.view.bind('itemEditCancel', function (item) {
that.editItemSave(item.id, item.title); that.editItemCancel(item.id);
}); });
that.view.bind('itemEditCancel', function (item) { that.view.bind('itemRemove', function (item) {
that.editItemCancel(item.id); that.removeItem(item.id);
}); });
that.view.bind('itemRemove', function (item) { that.view.bind('itemToggle', function (item) {
that.removeItem(item.id); that.toggleComplete(item.id, item.completed);
}); });
that.view.bind('itemToggle', function (item) { that.view.bind('removeCompleted', function () {
that.toggleComplete(item.id, item.completed); that.removeCompletedItems();
}); });
that.view.bind('removeCompleted', function () { that.view.bind('toggleAll', function (status) {
that.removeCompletedItems(); that.toggleAll(status.completed);
}); });
}
that.view.bind('toggleAll', function (status) { /**
that.toggleAll(status.completed); * Loads and initialises the view
}); *
* @param {string} '' | 'active' | 'completed'
*/
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 () {
var that = this;
that.model.read(function (data) {
that.view.render('showEntries', data);
});
};
/**
* Renders all active tasks
*/
Controller.prototype.showActive = function () {
var that = this;
that.model.read({completed: false}, function (data) {
that.view.render('showEntries', data);
});
};
/**
* Renders all completed tasks
*/
Controller.prototype.showCompleted = function () {
var that = this;
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) {
var that = this;
if (title.trim() === '') {
return;
} }
/** that.model.create(title, function () {
* Loads and initialises the view that.view.render('clearNewTodo');
* that._filter(true);
* @param {string} '' | 'active' | 'completed' });
*/ };
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 * Triggers the item editing mode.
* todo-list */
*/ Controller.prototype.editItem = function (id) {
Controller.prototype.showAll = function () { var that = this;
var that = this; that.model.read(id, function (data) {
that.model.read(function (data) { that.view.render('editItem', {id: id, title: data[0].title});
that.view.render('showEntries', data); });
};
/*
* Finishes the item editing mode successfully.
*/
Controller.prototype.editItemSave = function (id, title) {
var that = this;
if (title.trim()) {
that.model.update(id, {title: title}, function () {
that.view.render('editItemDone', {id: id, title: title});
}); });
}; } else {
that.removeItem(id);
}
};
/** /*
* Renders all active tasks * Cancels the item editing mode.
*/ */
Controller.prototype.showActive = function () { Controller.prototype.editItemCancel = function (id) {
var that = this; var that = this;
that.model.read({ completed: false }, function (data) { that.model.read(id, function (data) {
that.view.render('showEntries', 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) {
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 () {
var that = this;
that.model.read({completed: true}, function (data) {
data.forEach(function (item) {
that.removeItem(item.id);
}); });
}; });
/** that._filter();
* Renders all completed tasks };
*/
Controller.prototype.showCompleted = function () { /**
var that = this; * Give it an ID of a model and a checkbox and it will update the item
that.model.read({ completed: true }, function (data) { * in storage based on the checkbox's state.
that.view.render('showEntries', data); *
}); * @param {number} id The ID of the element to complete or uncomplete
}; * @param {object} checkbox The checkbox to check the state of complete
* or not
/** * @param {boolean|undefined} silent Prevent re-filtering the todo items
* 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.toggleComplete = function (id, completed, silent) {
*/ var that = this;
Controller.prototype.addItem = function (title) { that.model.update(id, {completed: completed}, function () {
var that = this; that.view.render('elementComplete', {
id: id,
if (title.trim() === '') { completed: completed
return;
}
that.model.create(title, function () {
that.view.render('clearNewTodo');
that._filter(true);
});
};
/*
* Triggers the item editing mode.
*/
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) {
var that = this;
if (title.trim()) {
that.model.update(id, {title: title}, function () {
that.view.render('editItemDone', {id: id, title: title});
});
} else {
that.removeItem(id);
}
};
/*
* Cancels the item editing mode.
*/
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) {
var that = this;
that.model.remove(id, function () {
that.view.render('removeItem', id);
}); });
});
if (!silent) {
that._filter(); that._filter();
}; }
};
/** /**
* Will remove all completed items from the DOM and storage. * Will toggle ALL checkboxes' on/off state and completeness of models.
*/ * Just pass in the event object.
Controller.prototype.removeCompletedItems = function () { */
var that = this; Controller.prototype.toggleAll = function (completed) {
that.model.read({ completed: true }, function (data) { var that = this;
data.forEach(function (item) { that.model.read({completed: !completed}, function (data) {
that.removeItem(item.id); 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 () {
var that = this;
that.model.getCount(function (todos) {
that.view.render('updateElementCount', todos.active);
that.view.render('clearCompletedButton', {
completed: todos.completed,
visible: todos.completed > 0
}); });
that._filter(); that.view.render('toggleAll', {checked: todos.completed === todos.total});
}; that.view.render('contentBlockVisibility', {visible: todos.total > 0});
});
};
/** /**
* Give it an ID of a model and a checkbox and it will update the item * Re-filters the todo items, based on the active route.
* in storage based on the checkbox's state. * @param {boolean|undefined} force forces a re-painting of todo items.
* */
* @param {number} id The ID of the element to complete or uncomplete Controller.prototype._filter = function (force) {
* @param {object} checkbox The checkbox to check the state of complete var activeRoute = this._activeRoute.charAt(0).toUpperCase() + this._activeRoute.substr(1);
* or not
* @param {boolean|undefined} silent Prevent re-filtering the todo items
*/
Controller.prototype.toggleComplete = function (id, completed, silent) {
var that = this;
that.model.update(id, { completed: completed }, function () {
that.view.render('elementComplete', {
id: id,
completed: completed
});
});
if (!silent) { // Update the elements on the page, which change with each completed todo
that._filter(); this._updateCount();
}
};
/** // If the last active route isn't "All", or we're switching routes, we
* Will toggle ALL checkboxes' on/off state and completeness of models. // re-create the todo item elements, calling:
* Just pass in the event object. // this.show[All|Active|Completed]();
*/ if (force || this._lastActiveRoute !== 'All' || this._lastActiveRoute !== activeRoute) {
Controller.prototype.toggleAll = function (completed) { this['show' + activeRoute]();
var that = this; }
that.model.read({ completed: !completed }, function (data) {
data.forEach(function (item) {
that.toggleComplete(item.id, completed, true);
});
});
that._filter(); this._lastActiveRoute = activeRoute;
}; };
/** /**
* Updates the pieces of the page which change depending on the remaining * Simply updates the filter nav's selected states
* number of todos. */
*/ Controller.prototype._updateFilterState = function (currentPage) {
Controller.prototype._updateCount = function () { // Store a reference to the active route, allowing us to re-filter todo
var that = this; // items as they are marked complete or incomplete.
that.model.getCount(function (todos) { this._activeRoute = currentPage;
that.view.render('updateElementCount', todos.active);
that.view.render('clearCompletedButton', {
completed: todos.completed,
visible: todos.completed > 0
});
that.view.render('toggleAll', {checked: todos.completed === todos.total}); if (currentPage === '') {
that.view.render('contentBlockVisibility', {visible: todos.total > 0}); this._activeRoute = 'All';
}); }
};
/** this._filter();
* 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) {
var activeRoute = this._activeRoute.charAt(0).toUpperCase() + this._activeRoute.substr(1);
// Update the elements on the page, which change with each completed todo this.view.render('setFilter', currentPage);
this._updateCount(); };
// If the last active route isn't "All", or we're switching routes, we // Export to window
// re-create the todo item elements, calling: window.app = window.app || {};
// this.show[All|Active|Completed](); window.app.Controller = Controller;
if (force || this._lastActiveRoute !== 'All' || this._lastActiveRoute !== activeRoute) {
this['show' + activeRoute]();
}
this._lastActiveRoute = activeRoute;
};
/**
* Simply updates the filter nav's selected states
*/
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;
if (currentPage === '') {
this._activeRoute = 'All';
}
this._filter();
this.view.render('setFilter', currentPage);
};
// Export to window
window.app = window.app || {};
window.app.Controller = Controller;
})(window);

View File

@ -1,52 +1,49 @@
/*global NodeList */ /*global NodeList */
(function (window) { 'use strict';
'use strict'; // Get element(s) by CSS selector:
window.qs = function (selector, scope) {
return (scope || document).querySelector(selector);
};
window.qsa = function (selector, scope) {
return (scope || document).querySelectorAll(selector);
};
// Get element(s) by CSS selector: // addEventListener wrapper:
window.qs = function (selector, scope) { window.$on = function (target, type, callback, useCapture) {
return (scope || document).querySelector(selector); target.addEventListener(type, callback, !!useCapture);
}; };
window.qsa = function (selector, scope) {
return (scope || document).querySelectorAll(selector);
};
// addEventListener wrapper: // Attach a handler to event for all elements that match the selector,
window.$on = function (target, type, callback, useCapture) { // now or in the future, based on a root element
target.addEventListener(type, callback, !!useCapture); window.$delegate = function (target, selector, type, handler) {
}; function dispatchEvent(event) {
var targetElement = event.target;
var potentialElements = window.qsa(selector, target);
var hasMatch = Array.prototype.indexOf.call(potentialElements, targetElement) >= 0;
// Attach a handler to event for all elements that match the selector, if (hasMatch) {
// now or in the future, based on a root element handler.call(targetElement, event);
window.$delegate = function (target, selector, type, handler) {
function dispatchEvent(event) {
var targetElement = event.target;
var potentialElements = window.qsa(selector, target);
var hasMatch = Array.prototype.indexOf.call(potentialElements, targetElement) >= 0;
if (hasMatch) {
handler.call(targetElement, event);
}
} }
}
// https://developer.mozilla.org/en-US/docs/Web/Events/blur // https://developer.mozilla.org/en-US/docs/Web/Events/blur
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;
} }
if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) { if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
return element.parentNode; return element.parentNode;
} }
return window.$parent(element.parentNode, tagName); return window.$parent(element.parentNode, tagName);
}; };
// 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,120 +1,119 @@
(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) {
this.storage = storage;
}
/** /**
* Creates a new Model instance and hooks up the storage. * Creates a new todo model
* *
* @constructor * @param {string} [title] The title of the task
* @param {object} storage A reference to the client side storage class * @param {function} [callback] The callback to fire after the model is created
*/ */
function Model(storage) { Model.prototype.create = function (title, callback) {
this.storage = storage; title = title || '';
callback = callback || function () {
};
var newItem = {
title: title.trim(),
completed: false
};
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
* 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 () {
};
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);
} else {
this.storage.find(query, callback);
} }
};
/** /**
* Creates a new todo model * Updates a model by giving it an ID, data to update, and a callback to fire when
* * the update is complete.
* @param {string} [title] The title of the task *
* @param {function} [callback] The callback to fire after the model is created * @param {number} id The id of the model to update
*/ * @param {object} data The properties to update and their new value
Model.prototype.create = function (title, callback) { * @param {function} callback The callback to fire when the update is complete.
title = title || ''; */
callback = callback || function () {}; Model.prototype.update = function (id, data, callback) {
this.storage.save(data, callback, id);
};
var newItem = { /**
title: title.trim(), * Removes a model from storage
completed: false *
}; * @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) {
this.storage.remove(id, callback);
};
this.storage.save(newItem, 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) {
this.storage.drop(callback);
};
/**
* Returns a count of all todos
*/
Model.prototype.getCount = function (callback) {
var todos = {
active: 0,
completed: 0,
total: 0
}; };
/** this.storage.findAll(function (data) {
* Finds and returns a model in storage. If no query is given it'll simply data.forEach(function (todo) {
* return everything. If you pass in a string or number it'll look that up as if (todo.completed) {
* the ID of the model to find. Lastly, you can pass it an object to match todos.completed++;
* against. } else {
* todos.active++;
* @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 () {};
if (queryType === 'function') { todos.total++;
callback = query;
return this.storage.findAll(callback);
} else if (queryType === 'string' || queryType === 'number') {
query = parseInt(query, 10);
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.
*
* @param {number} id The id of the model to update
* @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) {
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) {
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) {
this.storage.drop(callback);
};
/**
* Returns a count of all todos
*/
Model.prototype.getCount = function (callback) {
var todos = {
active: 0,
completed: 0,
total: 0
};
this.storage.findAll(function (data) {
data.forEach(function (todo) {
if (todo.completed) {
todos.completed++;
} else {
todos.active++;
}
todos.total++;
});
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,140 +1,140 @@
/*jshint eqeqeq:false */ /*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.
*
* @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 () {
};
/** this._dbName = name;
* 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 () {};
this._dbName = name; if (!localStorage[name]) {
var data = {
todos: []
};
if (!localStorage[name]) { localStorage[name] = JSON.stringify(data);
var data = {
todos: []
};
localStorage[name] = JSON.stringify(data);
}
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 }
*
* @param {object} query The query to match against (i.e. {foo: 'bar'}) /**
* @param {function} callback The callback to fire when the query has * Finds items based on a query given as a JS object
* completed running *
* * @param {object} query The query to match against (i.e. {foo: 'bar'})
* @example * @param {function} callback The callback to fire when the query has
* db.find({foo: 'bar', hello: 'world'}, function (data) { * completed running
*
* @example
* 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;
} }
var todos = JSON.parse(localStorage[this._dbName]).todos; var todos = JSON.parse(localStorage[this._dbName]).todos;
callback.call(this, todos.filter(function (todo) { callback.call(this, todos.filter(function (todo) {
for (var q in query) { for (var q in query) {
if (query[q] !== todo[q]) { if (query[q] !== todo[q]) {
return false; return false;
}
} }
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);
};
/**
* 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
*
* @param {object} updateData The data to save back into the DB
* @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) {
var data = JSON.parse(localStorage[this._dbName]);
var todos = data.todos;
callback = callback || function () {};
// If an ID was actually given, find the item and update each property
if (id) {
for (var i = 0; i < todos.length; i++) {
if (todos[i].id === id) {
for (var key in updateData) {
todos[i][key] = updateData[key];
}
break;
}
}
localStorage[this._dbName] = JSON.stringify(data);
callback.call(this, JSON.parse(localStorage[this._dbName]).todos);
} else {
// Generate an ID
updateData.id = new Date().getTime();
todos.push(updateData);
localStorage[this._dbName] = JSON.stringify(data);
callback.call(this, [updateData]);
} }
}; return true;
}));
};
/** /**
* Will remove an item from the Store based on its ID * Will retrieve all data from the collection
* *
* @param {number} id The ID of the item you want to remove * @param {function} callback The callback to fire upon retrieving data
* @param {function} callback The callback to fire after saving */
*/ Store.prototype.findAll = function (callback) {
Store.prototype.remove = function (id, callback) { callback = callback || function () {
var data = JSON.parse(localStorage[this._dbName]); };
var todos = data.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
* item, otherwise it'll simply update an existing item's properties
*
* @param {object} updateData The data to save back into the DB
* @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) {
var data = JSON.parse(localStorage[this._dbName]);
var todos = data.todos;
callback = callback || function () {
};
// If an ID was actually given, find the item and update each property
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) {
todos.splice(i, 1); for (var key in updateData) {
todos[i][key] = updateData[key];
}
break; break;
} }
} }
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);
}; } else {
// Generate an ID
updateData.id = new Date().getTime();
/** todos.push(updateData);
* Will drop all storage and start fresh localStorage[this._dbName] = JSON.stringify(data);
* callback.call(this, [updateData]);
* @param {function} callback The callback to fire after dropping the data }
*/ };
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 || {}; * Will remove an item from the Store based on its ID
window.app.Store = Store; *
})(window); * @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) {
var data = JSON.parse(localStorage[this._dbName]);
var todos = data.todos;
for (var i = 0; i < todos.length; i++) {
if (todos[i].id == id) {
todos.splice(i, 1);
break;
}
}
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) {
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;

View File

@ -1,114 +1,112 @@
/*jshint laxbreak:true */ /*jshint laxbreak:true */
(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,
reHasUnescapedHtml = new RegExp(reUnescapedHtml.source); 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 this.defaultTemplate
= '<li data-id="{{id}}" class="{{completed}}">' = '<li data-id="{{id}}" class="{{completed}}">'
+ '<div class="view">' + '<div class="view">'
+ '<input class="toggle" type="checkbox" {{checked}}>' + '<input class="toggle" type="checkbox" {{checked}}>'
+ '<label>{{title}}</label>' + '<label>{{title}}</label>'
+ '<button class="destroy"></button>' + '<button class="destroy"></button>'
+ '</div>' + '</div>'
+ '</li>'; + '</li>';
} }
/** /**
* Creates an <li> HTML string and returns it for placement in your app. * Creates an <li> HTML string and returns it for placement in your app.
* *
* NOTE: In real life you should be using a templating engine such as Mustache * NOTE: In real life you should be using a templating engine such as Mustache
* or Handlebars, however, this is a vanilla JS example. * or Handlebars, however, this is a vanilla JS example.
* *
* @param {object} data The object containing keys you want to find in the * @param {object} data The object containing keys you want to find in the
* template to replace. * template to replace.
* @returns {string} HTML String of an <li> element * @returns {string} HTML String of an <li> element
* *
* @example * @example
* view.show({ * view.show({
* id: 1, * id: 1,
* title: "Hello World", * title: "Hello World",
* completed: 0, * completed: 0,
* }); * });
*/ */
Template.prototype.show = function (data) { Template.prototype.show = function (data) {
var i, l; var i, l;
var view = ''; var view = '';
for (i = 0, l = data.length; i < l; i++) { for (i = 0, l = data.length; i < l; i++) {
var template = this.defaultTemplate; var template = this.defaultTemplate;
var completed = ''; var completed = '';
var checked = ''; var checked = '';
if (data[i].completed) { if (data[i].completed) {
completed = 'completed'; completed = 'completed';
checked = 'checked'; checked = 'checked';
}
template = template.replace('{{id}}', data[i].id);
template = template.replace('{{title}}', escape(data[i].title));
template = template.replace('{{completed}}', completed);
template = template.replace('{{checked}}', checked);
view = view + template;
} }
return view; template = template.replace('{{id}}', data[i].id);
}; template = template.replace('{{title}}', escape(data[i].title));
template = template.replace('{{completed}}', completed);
template = template.replace('{{checked}}', checked);
/** view = view + template;
* 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';
return '<strong>' + activeTodos + '</strong> item' + plural + ' left'; return view;
}; };
/** /**
* Updates the text within the "Clear completed" button * Displays a counter of how many to dos are left to complete
* *
* @param {[type]} completedTodos The number of completed todos. * @param {number} activeTodos The number of active todos.
* @returns {string} String containing the count * @returns {string} String containing the count
*/ */
Template.prototype.clearCompletedButton = function (completedTodos) { Template.prototype.itemCounter = function (activeTodos) {
if (completedTodos > 0) { var plural = activeTodos === 1 ? '' : 's';
return 'Clear completed';
} else {
return '';
}
};
// Export to window return '<strong>' + activeTodos + '</strong> item' + plural + ' left';
window.app = window.app || {}; };
window.app.Template = Template;
})(window); /**
* 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';
} else {
return '';
}
};
// Export to window
window.app = window.app || {};
window.app.Template = Template;

View File

@ -1,219 +1,216 @@
/*global qs, qsa, $on, $parent, $delegate */ /*global qs, qsa, $on, $parent, $delegate */
'use strict';
require('./helpers'); require('./helpers');
(function (window) { /**
'use strict'; * 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;
* View that abstracts away the browser's DOM completely. this.ESCAPE_KEY = 27;
* 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; this.$todoList = qs('.todo-list');
this.ESCAPE_KEY = 27; this.$todoItemCounter = qs('.todo-count');
this.$clearCompleted = qs('.clear-completed');
this.$main = qs('.main');
this.$footer = qs('.footer');
this.$toggleAll = qs('.toggle-all');
this.$newTodo = qs('.new-todo');
}
this.$todoList = qs('.todo-list'); View.prototype._removeItem = function (id) {
this.$todoItemCounter = qs('.todo-count'); var elem = qs('[data-id="' + id + '"]');
this.$clearCompleted = qs('.clear-completed');
this.$main = qs('.main');
this.$footer = qs('.footer');
this.$toggleAll = qs('.toggle-all');
this.$newTodo = qs('.new-todo');
}
View.prototype._removeItem = function (id) { if (elem) {
var elem = qs('[data-id="' + id + '"]'); this.$todoList.removeChild(elem);
}
};
if (elem) { View.prototype._clearCompletedButton = function (completedCount, visible) {
this.$todoList.removeChild(elem); this.$clearCompleted.innerHTML = this.template.clearCompletedButton(completedCount);
} this.$clearCompleted.style.display = visible ? 'block' : 'none';
}; };
View.prototype._clearCompletedButton = function (completedCount, visible) { View.prototype._setFilter = function (currentPage) {
this.$clearCompleted.innerHTML = this.template.clearCompletedButton(completedCount); qs('.filters .selected').className = '';
this.$clearCompleted.style.display = visible ? 'block' : 'none'; qs('.filters [href="#/' + currentPage + '"]').className = 'selected';
}; };
View.prototype._setFilter = function (currentPage) { View.prototype._elementComplete = function (id, completed) {
qs('.filters .selected').className = ''; var listItem = qs('[data-id="' + id + '"]');
qs('.filters [href="#/' + currentPage + '"]').className = 'selected';
};
View.prototype._elementComplete = function (id, completed) { if (!listItem) {
var listItem = qs('[data-id="' + id + '"]'); return;
}
if (!listItem) { listItem.className = completed ? 'completed' : '';
return;
}
listItem.className = completed ? 'completed' : ''; // In case it was toggled from an event and not by clicking the checkbox
qs('input', listItem).checked = completed;
};
// In case it was toggled from an event and not by clicking the checkbox View.prototype._editItem = function (id, title) {
qs('input', listItem).checked = completed; var listItem = qs('[data-id="' + id + '"]');
};
View.prototype._editItem = function (id, title) { if (!listItem) {
var listItem = qs('[data-id="' + id + '"]'); return;
}
if (!listItem) { listItem.className = listItem.className + ' editing';
return;
}
listItem.className = listItem.className + ' editing'; var input = document.createElement('input');
input.className = 'edit';
var input = document.createElement('input'); listItem.appendChild(input);
input.className = 'edit'; input.focus();
input.value = title;
};
listItem.appendChild(input); View.prototype._editItemDone = function (id, title) {
input.focus(); var listItem = qs('[data-id="' + id + '"]');
input.value = title;
};
View.prototype._editItemDone = function (id, title) { if (!listItem) {
var listItem = qs('[data-id="' + id + '"]'); return;
}
if (!listItem) { var input = qs('input.edit', listItem);
return; listItem.removeChild(input);
}
var input = qs('input.edit', listItem); listItem.className = listItem.className.replace('editing', '');
listItem.removeChild(input);
listItem.className = listItem.className.replace('editing', ''); qsa('label', listItem).forEach(function (label) {
label.textContent = title;
});
};
qsa('label', listItem).forEach(function (label) { View.prototype.render = function (viewCmd, parameter) {
label.textContent = title; var that = this;
}); var viewCommands = {
}; showEntries: function () {
that.$todoList.innerHTML = that.template.show(parameter);
},
removeItem: function () {
that._removeItem(parameter);
},
updateElementCount: function () {
that.$todoItemCounter.innerHTML = that.template.itemCounter(parameter);
},
clearCompletedButton: function () {
that._clearCompletedButton(parameter.completed, parameter.visible);
},
contentBlockVisibility: function () {
that.$main.style.display = that.$footer.style.display = parameter.visible ? 'block' : 'none';
},
toggleAll: function () {
that.$toggleAll.checked = parameter.checked;
},
setFilter: function () {
that._setFilter(parameter);
},
clearNewTodo: function () {
that.$newTodo.value = '';
},
elementComplete: function () {
that._elementComplete(parameter.id, parameter.completed);
},
editItem: function () {
that._editItem(parameter.id, parameter.title);
},
editItemDone: function () {
that._editItemDone(parameter.id, parameter.title);
}
};
View.prototype.render = function (viewCmd, parameter) { viewCommands[viewCmd]();
var that = this; };
var viewCommands = {
showEntries: function () {
that.$todoList.innerHTML = that.template.show(parameter);
},
removeItem: function () {
that._removeItem(parameter);
},
updateElementCount: function () {
that.$todoItemCounter.innerHTML = that.template.itemCounter(parameter);
},
clearCompletedButton: function () {
that._clearCompletedButton(parameter.completed, parameter.visible);
},
contentBlockVisibility: function () {
that.$main.style.display = that.$footer.style.display = parameter.visible ? 'block' : 'none';
},
toggleAll: function () {
that.$toggleAll.checked = parameter.checked;
},
setFilter: function () {
that._setFilter(parameter);
},
clearNewTodo: function () {
that.$newTodo.value = '';
},
elementComplete: function () {
that._elementComplete(parameter.id, parameter.completed);
},
editItem: function () {
that._editItem(parameter.id, parameter.title);
},
editItemDone: function () {
that._editItemDone(parameter.id, parameter.title);
}
};
viewCommands[viewCmd](); View.prototype._itemId = function (element) {
}; var li = $parent(element, 'li');
return parseInt(li.dataset.id, 10);
};
View.prototype._itemId = function (element) { View.prototype._bindItemEditDone = function (handler) {
var li = $parent(element, 'li'); var that = this;
return parseInt(li.dataset.id, 10); $delegate(that.$todoList, 'li .edit', 'blur', function () {
}; if (!this.dataset.iscanceled) {
handler({
id: that._itemId(this),
title: this.value
});
}
});
View.prototype._bindItemEditDone = function (handler) { $delegate(that.$todoList, 'li .edit', 'keypress', function (event) {
var that = this; if (event.keyCode === that.ENTER_KEY) {
$delegate(that.$todoList, 'li .edit', 'blur', function () { // Remove the cursor from the input when you hit enter just like if it
if (!this.dataset.iscanceled) { // were a real form
handler({ this.blur();
id: that._itemId(this), }
title: this.value });
}); };
}
});
$delegate(that.$todoList, 'li .edit', 'keypress', function (event) { View.prototype._bindItemEditCancel = function (handler) {
if (event.keyCode === that.ENTER_KEY) { var that = this;
// Remove the cursor from the input when you hit enter just like if it $delegate(that.$todoList, 'li .edit', 'keyup', function (event) {
// were a real form if (event.keyCode === that.ESCAPE_KEY) {
this.blur(); this.dataset.iscanceled = true;
} this.blur();
});
};
View.prototype._bindItemEditCancel = function (handler) { handler({id: that._itemId(this)});
var that = this; }
$delegate(that.$todoList, 'li .edit', 'keyup', function (event) { });
if (event.keyCode === that.ESCAPE_KEY) { };
this.dataset.iscanceled = true;
this.blur();
handler({id: that._itemId(this)}); View.prototype.bind = function (event, handler) {
} var that = this;
}); if (event === 'newTodo') {
}; $on(that.$newTodo, 'change', function () {
handler(that.$newTodo.value);
});
View.prototype.bind = function (event, handler) { } else if (event === 'removeCompleted') {
var that = this; $on(that.$clearCompleted, 'click', function () {
if (event === 'newTodo') { handler();
$on(that.$newTodo, 'change', function () { });
handler(that.$newTodo.value);
});
} else if (event === 'removeCompleted') { } else if (event === 'toggleAll') {
$on(that.$clearCompleted, 'click', function () { $on(that.$toggleAll, 'click', function () {
handler(); handler({completed: this.checked});
}); });
} else if (event === 'toggleAll') { } else if (event === 'itemEdit') {
$on(that.$toggleAll, 'click', function () { $delegate(that.$todoList, 'li label', 'dblclick', function () {
handler({completed: this.checked}); handler({id: that._itemId(this)});
}); });
} else if (event === 'itemEdit') { } else if (event === 'itemRemove') {
$delegate(that.$todoList, 'li label', 'dblclick', function () { $delegate(that.$todoList, '.destroy', 'click', function () {
handler({id: that._itemId(this)}); handler({id: that._itemId(this)});
}); });
} else if (event === 'itemRemove') { } else if (event === 'itemToggle') {
$delegate(that.$todoList, '.destroy', 'click', function () { $delegate(that.$todoList, '.toggle', 'click', function () {
handler({id: that._itemId(this)}); handler({
}); id: that._itemId(this),
completed: this.checked
});
});
} else if (event === 'itemToggle') { } else if (event === 'itemEditDone') {
$delegate(that.$todoList, '.toggle', 'click', function () { that._bindItemEditDone(handler);
handler({
id: that._itemId(this),
completed: this.checked
});
});
} else if (event === 'itemEditDone') { } else if (event === 'itemEditCancel') {
that._bindItemEditDone(handler); that._bindItemEditCancel(handler);
}
};
} else if (event === 'itemEditCancel') { // Export to window
that._bindItemEditCancel(handler); window.app = window.app || {};
} window.app.View = View;
};
// Export to window
window.app = window.app || {};
window.app.View = View;
}(window));