Commit 7d077b1d authored by Stephen Sawchuk's avatar Stephen Sawchuk

sammyjs upgraded + bower.

parent ff17a59f
{
"name": "todomvc-sammyjs",
"version": "0.0.0",
"dependencies": {
"sammy": "~0.7.4",
"jquery": "~1.9.1",
"todomvc-common": "~0.1.2"
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
// name: sammy
// version: 0.7.4
// Sammy.js / http://sammyjs.org
(function($, window) {
(function(factory){
// Support module loading scenarios
if (typeof define === 'function' && define.amd){
// AMD Anonymous Module
define(['jquery'], factory);
} else {
// No module loader (plain <script> tag) - put directly in global namespace
$.sammy = window.Sammy = factory($);
}
})(function($){
var Sammy,
PATH_REPLACER = "([^\/]+)",
PATH_NAME_MATCHER = /:([\w\d]+)/g,
QUERY_STRING_MATCHER = /\?([^#]*)?$/,
// mainly for making `arguments` an Array
_makeArray = function(nonarray) { return Array.prototype.slice.call(nonarray); },
// borrowed from jQuery
_isFunction = function( obj ) { return Object.prototype.toString.call(obj) === "[object Function]"; },
_isArray = function( obj ) { return Object.prototype.toString.call(obj) === "[object Array]"; },
_isRegExp = function( obj ) { return Object.prototype.toString.call(obj) === "[object RegExp]"; },
_decode = function( str ) { return decodeURIComponent((str || '').replace(/\+/g, ' ')); },
_encode = encodeURIComponent,
_escapeHTML = function(s) {
return String(s).replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
},
_routeWrapper = function(verb) {
return function() {
return this.route.apply(this, [verb].concat(Array.prototype.slice.call(arguments)));
};
},
_template_cache = {},
_has_history = !!(window.history && history.pushState),
loggers = [];
// `Sammy` (also aliased as $.sammy) is not only the namespace for a
// number of prototypes, its also a top level method that allows for easy
// creation/management of `Sammy.Application` instances. There are a
// number of different forms for `Sammy()` but each returns an instance
// of `Sammy.Application`. When a new instance is created using
// `Sammy` it is added to an Object called `Sammy.apps`. This
// provides for an easy way to get at existing Sammy applications. Only one
// instance is allowed per `element_selector` so when calling
// `Sammy('selector')` multiple times, the first time will create
// the application and the following times will extend the application
// already added to that selector.
//
// ### Example
//
// // returns the app at #main or a new app
// Sammy('#main')
//
// // equivalent to "new Sammy.Application", except appends to apps
// Sammy();
// Sammy(function() { ... });
//
// // extends the app at '#main' with function.
// Sammy('#main', function() { ... });
//
Sammy = function() {
var args = _makeArray(arguments),
app, selector;
Sammy.apps = Sammy.apps || {};
if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy()
return Sammy.apply(Sammy, ['body'].concat(args));
} else if (typeof (selector = args.shift()) == 'string') { // Sammy('#main')
app = Sammy.apps[selector] || new Sammy.Application();
app.element_selector = selector;
if (args.length > 0) {
$.each(args, function(i, plugin) {
app.use(plugin);
});
}
// if the selector changes make sure the reference in Sammy.apps changes
if (app.element_selector != selector) {
delete Sammy.apps[selector];
}
Sammy.apps[app.element_selector] = app;
return app;
}
};
Sammy.VERSION = '0.7.4';
// Add to the global logger pool. Takes a function that accepts an
// unknown number of arguments and should print them or send them somewhere
// The first argument is always a timestamp.
Sammy.addLogger = function(logger) {
loggers.push(logger);
};
// Sends a log message to each logger listed in the global
// loggers pool. Can take any number of arguments.
// Also prefixes the arguments with a timestamp.
Sammy.log = function() {
var args = _makeArray(arguments);
args.unshift("[" + Date() + "]");
$.each(loggers, function(i, logger) {
logger.apply(Sammy, args);
});
};
if (typeof window.console != 'undefined') {
if (_isFunction(window.console.log.apply)) {
Sammy.addLogger(function() {
window.console.log.apply(window.console, arguments);
});
} else {
Sammy.addLogger(function() {
window.console.log(arguments);
});
}
} else if (typeof console != 'undefined') {
Sammy.addLogger(function() {
console.log.apply(console, arguments);
});
}
$.extend(Sammy, {
makeArray: _makeArray,
isFunction: _isFunction,
isArray: _isArray
});
// Sammy.Object is the base for all other Sammy classes. It provides some useful
// functionality, including cloning, iterating, etc.
Sammy.Object = function(obj) { // constructor
return $.extend(this, obj || {});
};
$.extend(Sammy.Object.prototype, {
// Escape HTML in string, use in templates to prevent script injection.
// Also aliased as `h()`
escapeHTML: _escapeHTML,
h: _escapeHTML,
// Returns a copy of the object with Functions removed.
toHash: function() {
var json = {};
$.each(this, function(k,v) {
if (!_isFunction(v)) {
json[k] = v;
}
});
return json;
},
// Renders a simple HTML version of this Objects attributes.
// Does not render functions.
// For example. Given this Sammy.Object:
//
// var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
// s.toHTML()
// //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />'
//
toHTML: function() {
var display = "";
$.each(this, function(k, v) {
if (!_isFunction(v)) {
display += "<strong>" + k + "</strong> " + v + "<br />";
}
});
return display;
},
// Returns an array of keys for this object. If `attributes_only`
// is true will not return keys that map to a `function()`
keys: function(attributes_only) {
var keys = [];
for (var property in this) {
if (!_isFunction(this[property]) || !attributes_only) {
keys.push(property);
}
}
return keys;
},
// Checks if the object has a value at `key` and that the value is not empty
has: function(key) {
return this[key] && $.trim(this[key].toString()) !== '';
},
// convenience method to join as many arguments as you want
// by the first argument - useful for making paths
join: function() {
var args = _makeArray(arguments);
var delimiter = args.shift();
return args.join(delimiter);
},
// Shortcut to Sammy.log
log: function() {
Sammy.log.apply(Sammy, arguments);
},
// Returns a string representation of this object.
// if `include_functions` is true, it will also toString() the
// methods of this object. By default only prints the attributes.
toString: function(include_functions) {
var s = [];
$.each(this, function(k, v) {
if (!_isFunction(v) || include_functions) {
s.push('"' + k + '": ' + v.toString());
}
});
return "Sammy.Object: {" + s.join(',') + "}";
}
});
// Return whether the event targets this window.
Sammy.targetIsThisWindow = function targetIsThisWindow(event) {
var targetWindow = $(event.target).attr('target');
if ( !targetWindow || targetWindow === window.name || targetWindow === '_self' ) { return true; }
if ( targetWindow === '_blank' ) { return false; }
if ( targetWindow === 'top' && window === window.top ) { return true; }
return false;
};
// The DefaultLocationProxy is the default location proxy for all Sammy applications.
// A location proxy is a prototype that conforms to a simple interface. The purpose
// of a location proxy is to notify the Sammy.Application its bound to when the location
// or 'external state' changes.
//
// The `DefaultLocationProxy` watches for changes to the path of the current window and
// is also able to set the path based on changes in the application. It does this by
// using different methods depending on what is available in the current browser. In
// the latest and greatest browsers it used the HTML5 History API and the `pushState`
// `popState` events/methods. This allows you to use Sammy to serve a site behind normal
// URI paths as opposed to the older default of hash (#) based routing. Because the server
// can interpret the changed path on a refresh or re-entry, though, it requires additional
// support on the server side. If you'd like to force disable HTML5 history support, please
// use the `disable_push_state` setting on `Sammy.Application`. If pushState support
// is enabled, `DefaultLocationProxy` also binds to all links on the page. If a link is clicked
// that matches the current set of routes, the URL is changed using pushState instead of
// fully setting the location and the app is notified of the change.
//
// If the browser does not have support for HTML5 History, `DefaultLocationProxy` automatically
// falls back to the older hash based routing. The newest browsers (IE, Safari > 4, FF >= 3.6)
// support a 'onhashchange' DOM event, thats fired whenever the location.hash changes.
// In this situation the DefaultLocationProxy just binds to this event and delegates it to
// the application. In the case of older browsers a poller is set up to track changes to the
// hash.
Sammy.DefaultLocationProxy = function(app, run_interval_every) {
this.app = app;
// set is native to false and start the poller immediately
this.is_native = false;
this.has_history = _has_history;
this._startPolling(run_interval_every);
};
Sammy.DefaultLocationProxy.fullPath = function(location_obj) {
// Bypass the `window.location.hash` attribute. If a question mark
// appears in the hash IE6 will strip it and all of the following
// characters from `window.location.hash`.
var matches = location_obj.toString().match(/^[^#]*(#.+)$/);
var hash = matches ? matches[1] : '';
return [location_obj.pathname, location_obj.search, hash].join('');
};
$.extend(Sammy.DefaultLocationProxy.prototype , {
// bind the proxy events to the current app.
bind: function() {
var proxy = this, app = this.app, lp = Sammy.DefaultLocationProxy;
$(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) {
// if we receive a native hash change event, set the proxy accordingly
// and stop polling
if (proxy.is_native === false && !non_native) {
proxy.is_native = true;
window.clearInterval(lp._interval);
lp._interval = null;
}
app.trigger('location-changed');
});
if (_has_history && !app.disable_push_state) {
// bind to popstate
$(window).bind('popstate.' + this.app.eventNamespace(), function(e) {
app.trigger('location-changed');
});
// bind to link clicks that have routes
$(document).delegate('a', 'click.history-' + this.app.eventNamespace(), function (e) {
if (e.isDefaultPrevented() || e.metaKey || e.ctrlKey) {
return;
}
var full_path = lp.fullPath(this);
if (this.hostname == window.location.hostname &&
app.lookupRoute('get', full_path) &&
Sammy.targetIsThisWindow(e)) {
e.preventDefault();
proxy.setLocation(full_path);
return false;
}
});
}
if (!lp._bindings) {
lp._bindings = 0;
}
lp._bindings++;
},
// unbind the proxy events from the current app
unbind: function() {
$(window).unbind('hashchange.' + this.app.eventNamespace());
$(window).unbind('popstate.' + this.app.eventNamespace());
$(document).undelegate('a', 'click.history-' + this.app.eventNamespace());
Sammy.DefaultLocationProxy._bindings--;
if (Sammy.DefaultLocationProxy._bindings <= 0) {
window.clearInterval(Sammy.DefaultLocationProxy._interval);
Sammy.DefaultLocationProxy._interval = null;
}
},
// get the current location from the hash.
getLocation: function() {
return Sammy.DefaultLocationProxy.fullPath(window.location);
},
// set the current location to `new_location`
setLocation: function(new_location) {
if (/^([^#\/]|$)/.test(new_location)) { // non-prefixed url
if (_has_history && !this.app.disable_push_state) {
new_location = '/' + new_location;
} else {
new_location = '#!/' + new_location;
}
}
if (new_location != this.getLocation()) {
// HTML5 History exists and new_location is a full path
if (_has_history && !this.app.disable_push_state && /^\//.test(new_location)) {
history.pushState({ path: new_location }, window.title, new_location);
this.app.trigger('location-changed');
} else {
return (window.location = new_location);
}
}
},
_startPolling: function(every) {
// set up interval
var proxy = this;
if (!Sammy.DefaultLocationProxy._interval) {
if (!every) { every = 10; }
var hashCheck = function() {
var current_location = proxy.getLocation();
if (typeof Sammy.DefaultLocationProxy._last_location == 'undefined' ||
current_location != Sammy.DefaultLocationProxy._last_location) {
window.setTimeout(function() {
$(window).trigger('hashchange', [true]);
}, 0);
}
Sammy.DefaultLocationProxy._last_location = current_location;
};
hashCheck();
Sammy.DefaultLocationProxy._interval = window.setInterval(hashCheck, every);
}
}
});
// Sammy.Application is the Base prototype for defining 'applications'.
// An 'application' is a collection of 'routes' and bound events that is
// attached to an element when `run()` is called.
// The only argument an 'app_function' is evaluated within the context of the application.
Sammy.Application = function(app_function) {
var app = this;
this.routes = {};
this.listeners = new Sammy.Object({});
this.arounds = [];
this.befores = [];
// generate a unique namespace
this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10);
this.context_prototype = function() { Sammy.EventContext.apply(this, arguments); };
this.context_prototype.prototype = new Sammy.EventContext();
if (_isFunction(app_function)) {
app_function.apply(this, [this]);
}
// set the location proxy if not defined to the default (DefaultLocationProxy)
if (!this._location_proxy) {
this.setLocationProxy(new Sammy.DefaultLocationProxy(this, this.run_interval_every));
}
if (this.debug) {
this.bindToAllEvents(function(e, data) {
app.log(app.toString(), e.cleaned_type, data || {});
});
}
};
Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, {
// the four route verbs
ROUTE_VERBS: ['get','post','put','delete'],
// An array of the default events triggered by the
// application during its lifecycle
APP_EVENTS: ['run', 'unload', 'lookup-route', 'run-route', 'route-found', 'event-context-before', 'event-context-after', 'changed', 'error', 'check-form-submission', 'redirect', 'location-changed'],
_last_route: null,
_location_proxy: null,
_running: false,
// Defines what element the application is bound to. Provide a selector
// (parseable by `jQuery()`) and this will be used by `$element()`
element_selector: 'body',
// When set to true, logs all of the default events using `log()`
debug: false,
// When set to true, and the error() handler is not overridden, will actually
// raise JS errors in routes (500) and when routes can't be found (404)
raise_errors: false,
// The time in milliseconds that the URL is queried for changes
run_interval_every: 50,
// if using the `DefaultLocationProxy` setting this to true will force the app to use
// traditional hash based routing as opposed to the new HTML5 PushState support
disable_push_state: false,
// The default template engine to use when using `partial()` in an
// `EventContext`. `template_engine` can either be a string that
// corresponds to the name of a method/helper on EventContext or it can be a function
// that takes two arguments, the content of the unrendered partial and an optional
// JS object that contains interpolation data. Template engine is only called/referred
// to if the extension of the partial is null or unknown. See `partial()`
// for more information
template_engine: null,
// //=> Sammy.Application: body
toString: function() {
return 'Sammy.Application:' + this.element_selector;
},
// returns a jQuery object of the Applications bound element.
$element: function(selector) {
return selector ? $(this.element_selector).find(selector) : $(this.element_selector);
},
// `use()` is the entry point for including Sammy plugins.
// The first argument to use should be a function() that is evaluated
// in the context of the current application, just like the `app_function`
// argument to the `Sammy.Application` constructor.
//
// Any additional arguments are passed to the app function sequentially.
//
// For much more detail about plugins, check out:
// [http://sammyjs.org/docs/plugins](http://sammyjs.org/docs/plugins)
//
// ### Example
//
// var MyPlugin = function(app, prepend) {
//
// this.helpers({
// myhelper: function(text) {
// alert(prepend + " " + text);
// }
// });
//
// };
//
// var app = $.sammy(function() {
//
// this.use(MyPlugin, 'This is my plugin');
//
// this.get('#/', function() {
// this.myhelper('and dont you forget it!');
// //=> Alerts: This is my plugin and dont you forget it!
// });
//
// });
//
// If plugin is passed as a string it assumes your are trying to load
// Sammy."Plugin". This is the preferred way of loading core Sammy plugins
// as it allows for better error-messaging.
//
// ### Example
//
// $.sammy(function() {
// this.use('Mustache'); //=> Sammy.Mustache
// this.use('Storage'); //=> Sammy.Storage
// });
//
use: function() {
// flatten the arguments
var args = _makeArray(arguments),
plugin = args.shift(),
plugin_name = plugin || '';
try {
args.unshift(this);
if (typeof plugin == 'string') {
plugin_name = 'Sammy.' + plugin;
plugin = Sammy[plugin];
}
plugin.apply(this, args);
} catch(e) {
if (typeof plugin === 'undefined') {
this.error("Plugin Error: called use() but plugin (" + plugin_name.toString() + ") is not defined", e);
} else if (!_isFunction(plugin)) {
this.error("Plugin Error: called use() but '" + plugin_name.toString() + "' is not a function", e);
} else {
this.error("Plugin Error", e);
}
}
return this;
},
// Sets the location proxy for the current app. By default this is set to
// a new `Sammy.DefaultLocationProxy` on initialization. However, you can set
// the location_proxy inside you're app function to give your app a custom
// location mechanism. See `Sammy.DefaultLocationProxy` and `Sammy.DataLocationProxy`
// for examples.
//
// `setLocationProxy()` takes an initialized location proxy.
//
// ### Example
//
// // to bind to data instead of the default hash;
// var app = $.sammy(function() {
// this.setLocationProxy(new Sammy.DataLocationProxy(this));
// });
//
setLocationProxy: function(new_proxy) {
var original_proxy = this._location_proxy;
this._location_proxy = new_proxy;
if (this.isRunning()) {
if (original_proxy) {
// if there is already a location proxy, unbind it.
original_proxy.unbind();
}
this._location_proxy.bind();
}
},
// provide log() override for inside an app that includes the relevant application element_selector
log: function() {
Sammy.log.apply(Sammy, Array.prototype.concat.apply([this.element_selector],arguments));
},
// `route()` is the main method for defining routes within an application.
// For great detail on routes, check out:
// [http://sammyjs.org/docs/routes](http://sammyjs.org/docs/routes)
//
// This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.)
//
// ### Arguments
//
// * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each
// of the ROUTE_VERBS. If only two arguments are passed,
// the first argument is the path, the second is the callback and the verb
// is assumed to be 'any'.
// * `path` A Regexp or a String representing the path to match to invoke this verb.
// * `callback` A Function that is called/evaluated when the route is run see: `runRoute()`.
// It is also possible to pass a string as the callback, which is looked up as the name
// of a method on the application.
//
route: function(verb, path) {
var app = this, param_names = [], add_route, path_match, callback = Array.prototype.slice.call(arguments,2);
// if the method signature is just (path, callback)
// assume the verb is 'any'
if (callback.length === 0 && _isFunction(path)) {
path = verb;
callback = [path];
verb = 'any';
}
verb = verb.toLowerCase(); // ensure verb is lower case
// if path is a string turn it into a regex
if (path.constructor == String) {
// Needs to be explicitly set because IE will maintain the index unless NULL is returned,
// which means that with two consecutive routes that contain params, the second set of params will not be found and end up in splat instead of params
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex
PATH_NAME_MATCHER.lastIndex = 0;
// find the names
while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) {
param_names.push(path_match[1]);
}
// replace with the path replacement
path = new RegExp(path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$");
}
// lookup callbacks
$.each(callback,function(i,cb){
if (typeof(cb) === 'string') {
callback[i] = app[cb];
}
});
add_route = function(with_verb) {
var r = {verb: with_verb, path: path, callback: callback, param_names: param_names};
// add route to routes array
app.routes[with_verb] = app.routes[with_verb] || [];
// place routes in order of definition
app.routes[with_verb].push(r);
};
if (verb === 'any') {
$.each(this.ROUTE_VERBS, function(i, v) { add_route(v); });
} else {
add_route(verb);
}
// return the app
return this;
},
// Alias for route('get', ...)
get: _routeWrapper('get'),
// Alias for route('post', ...)
post: _routeWrapper('post'),
// Alias for route('put', ...)
put: _routeWrapper('put'),
// Alias for route('delete', ...)
del: _routeWrapper('delete'),
// Alias for route('any', ...)
any: _routeWrapper('any'),
// `mapRoutes` takes an array of arrays, each array being passed to route()
// as arguments, this allows for mass definition of routes. Another benefit is
// this makes it possible/easier to load routes via remote JSON.
//
// ### Example
//
// var app = $.sammy(function() {
//
// this.mapRoutes([
// ['get', '#/', function() { this.log('index'); }],
// // strings in callbacks are looked up as methods on the app
// ['post', '#/create', 'addUser'],
// // No verb assumes 'any' as the verb
// [/dowhatever/, function() { this.log(this.verb, this.path)}];
// ]);
// });
//
mapRoutes: function(route_array) {
var app = this;
$.each(route_array, function(i, route_args) {
app.route.apply(app, route_args);
});
return this;
},
// A unique event namespace defined per application.
// All events bound with `bind()` are automatically bound within this space.
eventNamespace: function() {
return ['sammy-app', this.namespace].join('-');
},
// Works just like `jQuery.fn.bind()` with a couple notable differences.
//
// * It binds all events to the application element
// * All events are bound within the `eventNamespace()`
// * Events are not actually bound until the application is started with `run()`
// * callbacks are evaluated within the context of a Sammy.EventContext
//
bind: function(name, data, callback) {
var app = this;
// build the callback
// if the arity is 2, callback is the second argument
if (typeof callback == 'undefined') { callback = data; }
var listener_callback = function() {
// pull off the context from the arguments to the callback
var e, context, data;
e = arguments[0];
data = arguments[1];
if (data && data.context) {
context = data.context;
delete data.context;
} else {
context = new app.context_prototype(app, 'bind', e.type, data, e.target);
}
e.cleaned_type = e.type.replace(app.eventNamespace(), '');
callback.apply(context, [e, data]);
};
// it could be that the app element doesnt exist yet
// so attach to the listeners array and then run()
// will actually bind the event.
if (!this.listeners[name]) { this.listeners[name] = []; }
this.listeners[name].push(listener_callback);
if (this.isRunning()) {
// if the app is running
// *actually* bind the event to the app element
this._listen(name, listener_callback);
}
return this;
},
// Triggers custom events defined with `bind()`
//
// ### Arguments
//
// * `name` The name of the event. Automatically prefixed with the `eventNamespace()`
// * `data` An optional Object that can be passed to the bound callback.
// * `context` An optional context/Object in which to execute the bound callback.
// If no context is supplied a the context is a new `Sammy.EventContext`
//
trigger: function(name, data) {
this.$element().trigger([name, this.eventNamespace()].join('.'), [data]);
return this;
},
// Reruns the current route
refresh: function() {
this.last_location = null;
this.trigger('location-changed');
return this;
},
// Takes a single callback that is pushed on to a stack.
// Before any route is run, the callbacks are evaluated in order within
// the current `Sammy.EventContext`
//
// If any of the callbacks explicitly return false, execution of any
// further callbacks and the route itself is halted.
//
// You can also provide a set of options that will define when to run this
// before based on the route it proceeds.
//
// ### Example
//
// var app = $.sammy(function() {
//
// // will run at #/route but not at #/
// this.before('#/route', function() {
// //...
// });
//
// // will run at #/ but not at #/route
// this.before({except: {path: '#/route'}}, function() {
// this.log('not before #/route');
// });
//
// this.get('#/', function() {});
//
// this.get('#/route', function() {});
//
// });
//
// See `contextMatchesOptions()` for a full list of supported options
//
before: function(options, callback) {
if (_isFunction(options)) {
callback = options;
options = {};
}
this.befores.push([options, callback]);
return this;
},
// A shortcut for binding a callback to be run after a route is executed.
// After callbacks have no guarunteed order.
after: function(callback) {
return this.bind('event-context-after', callback);
},
// Adds an around filter to the application. around filters are functions
// that take a single argument `callback` which is the entire route
// execution path wrapped up in a closure. This means you can decide whether
// or not to proceed with execution by not invoking `callback` or,
// more usefully wrapping callback inside the result of an asynchronous execution.
//
// ### Example
//
// The most common use case for around() is calling a _possibly_ async function
// and executing the route within the functions callback:
//
// var app = $.sammy(function() {
//
// var current_user = false;
//
// function checkLoggedIn(callback) {
// // /session returns a JSON representation of the logged in user
// // or an empty object
// if (!current_user) {
// $.getJSON('/session', function(json) {
// if (json.login) {
// // show the user as logged in
// current_user = json;
// // execute the route path
// callback();
// } else {
// // show the user as not logged in
// current_user = false;
// // the context of aroundFilters is an EventContext
// this.redirect('#/login');
// }
// });
// } else {
// // execute the route path
// callback();
// }
// };
//
// this.around(checkLoggedIn);
//
// });
//
around: function(callback) {
this.arounds.push(callback);
return this;
},
// Adds a onComplete function to the application. onComplete functions are executed
// at the end of a chain of route callbacks, if they call next(). Unlike after,
// which is called as soon as the route is complete, onComplete is like a final next()
// for all routes, and is thus run asynchronously
//
// ### Example
//
// app.get('/chain',function(context,next){
// console.log('chain1');
// next();
// },function(context,next){
// console.log('chain2');
// next();
// });
// app.get('/link',function(context,next){
// console.log('link1');
// next();
// },function(context,next){
// console.log('link2');
// next();
// });
// app.onComplete(function(){
// console.log("Running finally")
// });
//
// If you go to '/chain', you will get the following messages:
// chain1
// chain2
// Running onComplete
//
//
// If you go to /link, you will get the following messages:
// link1
// link2
// Running onComplete
//
// It really comes to play when doing asynchronous:
// app.get('/chain',function(context,next){
// $.get('/my/url',function(){
// console.log('chain1');
// next();
// })
// },function(context,next){
// console.log('chain2');
// next();
// });
//
onComplete: function(callback) {
this._onComplete = callback;
return this;
},
// Returns `true` if the current application is running.
isRunning: function() {
return this._running;
},
// Helpers extends the EventContext prototype specific to this app.
// This allows you to define app specific helper functions that can be used
// whenever you're inside of an event context (templates, routes, bind).
//
// ### Example
//
// var app = $.sammy(function() {
//
// helpers({
// upcase: function(text) {
// return text.toString().toUpperCase();
// }
// });
//
// get('#/', function() { with(this) {
// // inside of this context I can use the helpers
// $('#main').html(upcase($('#main').text());
// }});
//
// });
//
//
// ### Arguments
//
// * `extensions` An object collection of functions to extend the context.
//
helpers: function(extensions) {
$.extend(this.context_prototype.prototype, extensions);
return this;
},
// Helper extends the event context just like `helpers()` but does it
// a single method at a time. This is especially useful for dynamically named
// helpers
//
// ### Example
//
// // Trivial example that adds 3 helper methods to the context dynamically
// var app = $.sammy(function(app) {
//
// $.each([1,2,3], function(i, num) {
// app.helper('helper' + num, function() {
// this.log("I'm helper number " + num);
// });
// });
//
// this.get('#/', function() {
// this.helper2(); //=> I'm helper number 2
// });
// });
//
// ### Arguments
//
// * `name` The name of the method
// * `method` The function to be added to the prototype at `name`
//
helper: function(name, method) {
this.context_prototype.prototype[name] = method;
return this;
},
// Actually starts the application's lifecycle. `run()` should be invoked
// within a document.ready block to ensure the DOM exists before binding events, etc.
//
// ### Example
//
// var app = $.sammy(function() { ... }); // your application
// $(function() { // document.ready
// app.run();
// });
//
// ### Arguments
//
// * `start_url` Optionally, a String can be passed which the App will redirect to
// after the events/routes have been bound.
run: function(start_url) {
if (this.isRunning()) { return false; }
var app = this;
// actually bind all the listeners
$.each(this.listeners.toHash(), function(name, callbacks) {
$.each(callbacks, function(i, listener_callback) {
app._listen(name, listener_callback);
});
});
this.trigger('run', {start_url: start_url});
this._running = true;
// set last location
this.last_location = null;
if (!(/\#(.+)/.test(this.getLocation())) && typeof start_url != 'undefined') {
this.setLocation(start_url);
}
// check url
this._checkLocation();
this._location_proxy.bind();
this.bind('location-changed', function() {
app._checkLocation();
});
// bind to submit to capture post/put/delete routes
this.bind('submit', function(e) {
if ( !Sammy.targetIsThisWindow(e) ) { return true; }
var returned = app._checkFormSubmission($(e.target).closest('form'));
return (returned === false) ? e.preventDefault() : false;
});
// bind unload to body unload
$(window).bind('unload', function() {
app.unload();
});
// trigger html changed
return this.trigger('changed');
},
// The opposite of `run()`, un-binds all event listeners and intervals
// `run()` Automatically binds a `onunload` event to run this when
// the document is closed.
unload: function() {
if (!this.isRunning()) { return false; }
var app = this;
this.trigger('unload');
// clear interval
this._location_proxy.unbind();
// unbind form submits
this.$element().unbind('submit').removeClass(app.eventNamespace());
// unbind all events
$.each(this.listeners.toHash() , function(name, listeners) {
$.each(listeners, function(i, listener_callback) {
app._unlisten(name, listener_callback);
});
});
this._running = false;
return this;
},
// Not only runs `unbind` but also destroys the app reference.
destroy: function() {
this.unload();
delete Sammy.apps[this.element_selector];
return this;
},
// Will bind a single callback function to every event that is already
// being listened to in the app. This includes all the `APP_EVENTS`
// as well as any custom events defined with `bind()`.
//
// Used internally for debug logging.
bindToAllEvents: function(callback) {
var app = this;
// bind to the APP_EVENTS first
$.each(this.APP_EVENTS, function(i, e) {
app.bind(e, callback);
});
// next, bind to listener names (only if they dont exist in APP_EVENTS)
$.each(this.listeners.keys(true), function(i, name) {
if ($.inArray(name, app.APP_EVENTS) == -1) {
app.bind(name, callback);
}
});
return this;
},
// Returns a copy of the given path with any query string after the hash
// removed.
routablePath: function(path) {
return path.replace(QUERY_STRING_MATCHER, '');
},
// Given a verb and a String path, will return either a route object or false
// if a matching route can be found within the current defined set.
lookupRoute: function(verb, path) {
var app = this, routed = false, i = 0, l, route;
if (typeof this.routes[verb] != 'undefined') {
l = this.routes[verb].length;
for (; i < l; i++) {
route = this.routes[verb][i];
if (app.routablePath(path).match(route.path)) {
routed = route;
break;
}
}
}
return routed;
},
// First, invokes `lookupRoute()` and if a route is found, parses the
// possible URL params and then invokes the route's callback within a new
// `Sammy.EventContext`. If the route can not be found, it calls
// `notFound()`. If `raise_errors` is set to `true` and
// the `error()` has not been overridden, it will throw an actual JS
// error.
//
// You probably will never have to call this directly.
//
// ### Arguments
//
// * `verb` A String for the verb.
// * `path` A String path to lookup.
// * `params` An Object of Params pulled from the URI or passed directly.
//
// ### Returns
//
// Either returns the value returned by the route callback or raises a 404 Not Found error.
//
runRoute: function(verb, path, params, target) {
var app = this,
route = this.lookupRoute(verb, path),
context,
wrapped_route,
arounds,
around,
befores,
before,
callback_args,
path_params,
final_returned;
if (this.debug) {
this.log('runRoute', [verb, path].join(' '));
}
this.trigger('run-route', {verb: verb, path: path, params: params});
if (typeof params == 'undefined') { params = {}; }
$.extend(params, this._parseQueryString(path));
if (route) {
this.trigger('route-found', {route: route});
// pull out the params from the path
if ((path_params = route.path.exec(this.routablePath(path))) !== null) {
// first match is the full path
path_params.shift();
// for each of the matches
$.each(path_params, function(i, param) {
// if theres a matching param name
if (route.param_names[i]) {
// set the name to the match
params[route.param_names[i]] = _decode(param);
} else {
// initialize 'splat'
if (!params.splat) { params.splat = []; }
params.splat.push(_decode(param));
}
});
}
// set event context
context = new this.context_prototype(this, verb, path, params, target);
// ensure arrays
arounds = this.arounds.slice(0);
befores = this.befores.slice(0);
// set the callback args to the context + contents of the splat
callback_args = [context];
if (params.splat) {
callback_args = callback_args.concat(params.splat);
}
// wrap the route up with the before filters
wrapped_route = function() {
var returned, i, nextRoute;
while (befores.length > 0) {
before = befores.shift();
// check the options
if (app.contextMatchesOptions(context, before[0])) {
returned = before[1].apply(context, [context]);
if (returned === false) { return false; }
}
}
app.last_route = route;
context.trigger('event-context-before', {context: context});
// run multiple callbacks
if (typeof(route.callback) === "function") {
route.callback = [route.callback];
}
if (route.callback && route.callback.length) {
i = -1;
nextRoute = function() {
i++;
if (route.callback[i]) {
returned = route.callback[i].apply(context,callback_args);
} else if (app._onComplete && typeof(app._onComplete === "function")) {
app._onComplete(context);
}
};
callback_args.push(nextRoute);
nextRoute();
}
context.trigger('event-context-after', {context: context});
return returned;
};
$.each(arounds.reverse(), function(i, around) {
var last_wrapped_route = wrapped_route;
wrapped_route = function() { return around.apply(context, [last_wrapped_route]); };
});
try {
final_returned = wrapped_route();
} catch(e) {
this.error(['500 Error', verb, path].join(' '), e);
}
return final_returned;
} else {
return this.notFound(verb, path);
}
},
// Matches an object of options against an `EventContext` like object that
// contains `path` and `verb` attributes. Internally Sammy uses this
// for matching `before()` filters against specific options. You can set the
// object to _only_ match certain paths or verbs, or match all paths or verbs _except_
// those that match the options.
//
// ### Example
//
// var app = $.sammy(),
// context = {verb: 'get', path: '#/mypath'};
//
// // match against a path string
// app.contextMatchesOptions(context, '#/mypath'); //=> true
// app.contextMatchesOptions(context, '#/otherpath'); //=> false
// // equivalent to
// app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true
// app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false
// // match against a path regexp
// app.contextMatchesOptions(context, /path/); //=> true
// app.contextMatchesOptions(context, /^path/); //=> false
// // match only a verb
// app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true
// app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false
// // match all except a verb
// app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true
// app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false
// // match all except a path
// app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true
// app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false
// // match multiple paths
// app.contextMatchesOptions(context, {path: ['#/mypath', '#/otherpath']}); //=> true
// app.contextMatchesOptions(context, {path: ['#/otherpath', '#/thirdpath']}); //=> false
// // equivalent to
// app.contextMatchesOptions(context, {only: {path: ['#/mypath', '#/otherpath']}}); //=> true
// app.contextMatchesOptions(context, {only: {path: ['#/otherpath', '#/thirdpath']}}); //=> false
// // match all except multiple paths
// app.contextMatchesOptions(context, {except: {path: ['#/mypath', '#/otherpath']}}); //=> false
// app.contextMatchesOptions(context, {except: {path: ['#/otherpath', '#/thirdpath']}}); //=> true
//
contextMatchesOptions: function(context, match_options, positive) {
var options = match_options;
// normalize options
if (typeof options === 'string' || _isRegExp(options)) {
options = {path: options};
}
if (typeof positive === 'undefined') {
positive = true;
}
// empty options always match
if ($.isEmptyObject(options)) {
return true;
}
// Do we have to match against multiple paths?
if (_isArray(options.path)){
var results, numopt, opts, len;
results = [];
for (numopt = 0, len = options.path.length; numopt < len; numopt += 1) {
opts = $.extend({}, options, {path: options.path[numopt]});
results.push(this.contextMatchesOptions(context, opts));
}
var matched = $.inArray(true, results) > -1 ? true : false;
return positive ? matched : !matched;
}
if (options.only) {
return this.contextMatchesOptions(context, options.only, true);
} else if (options.except) {
return this.contextMatchesOptions(context, options.except, false);
}
var path_matched = true, verb_matched = true;
if (options.path) {
if (!_isRegExp(options.path)) {
options.path = new RegExp(options.path.toString() + '$');
}
path_matched = options.path.test(context.path);
}
if (options.verb) {
if(typeof options.verb === 'string') {
verb_matched = options.verb === context.verb;
} else {
verb_matched = options.verb.indexOf(context.verb) > -1;
}
}
return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched);
},
// Delegates to the `location_proxy` to get the current location.
// See `Sammy.DefaultLocationProxy` for more info on location proxies.
getLocation: function() {
return this._location_proxy.getLocation();
},
// Delegates to the `location_proxy` to set the current location.
// See `Sammy.DefaultLocationProxy` for more info on location proxies.
//
// ### Arguments
//
// * `new_location` A new location string (e.g. '#/')
//
setLocation: function(new_location) {
return this._location_proxy.setLocation(new_location);
},
// Swaps the content of `$element()` with `content`
// You can override this method to provide an alternate swap behavior
// for `EventContext.partial()`.
//
// ### Example
//
// var app = $.sammy(function() {
//
// // implements a 'fade out'/'fade in'
// this.swap = function(content, callback) {
// var context = this;
// context.$element().fadeOut('slow', function() {
// context.$element().html(content);
// context.$element().fadeIn('slow', function() {
// if (callback) {
// callback.apply();
// }
// });
// });
// };
//
// });
//
swap: function(content, callback) {
var $el = this.$element().html(content);
if (_isFunction(callback)) { callback(content); }
return $el;
},
// a simple global cache for templates. Uses the same semantics as
// `Sammy.Cache` and `Sammy.Storage` so can easily be replaced with
// a persistent storage that lasts beyond the current request.
templateCache: function(key, value) {
if (typeof value != 'undefined') {
return _template_cache[key] = value;
} else {
return _template_cache[key];
}
},
// clear the templateCache
clearTemplateCache: function() {
return (_template_cache = {});
},
// This throws a '404 Not Found' error by invoking `error()`.
// Override this method or `error()` to provide custom
// 404 behavior (i.e redirecting to / or showing a warning)
notFound: function(verb, path) {
var ret = this.error(['404 Not Found', verb, path].join(' '));
return (verb === 'get') ? ret : true;
},
// The base error handler takes a string `message` and an `Error`
// object. If `raise_errors` is set to `true` on the app level,
// this will re-throw the error to the browser. Otherwise it will send the error
// to `log()`. Override this method to provide custom error handling
// e.g logging to a server side component or displaying some feedback to the
// user.
error: function(message, original_error) {
if (!original_error) { original_error = new Error(); }
original_error.message = [message, original_error.message].join(' ');
this.trigger('error', {message: original_error.message, error: original_error});
if (this.raise_errors) {
throw(original_error);
} else {
this.log(original_error.message, original_error);
}
},
_checkLocation: function() {
var location, returned;
// get current location
location = this.getLocation();
// compare to see if hash has changed
if (!this.last_location || this.last_location[0] != 'get' || this.last_location[1] != location) {
// reset last location
this.last_location = ['get', location];
// lookup route for current hash
returned = this.runRoute('get', location);
}
return returned;
},
_getFormVerb: function(form) {
var $form = $(form), verb, $_method;
$_method = $form.find('input[name="_method"]');
if ($_method.length > 0) { verb = $_method.val(); }
if (!verb) { verb = $form[0].getAttribute('method'); }
if (!verb || verb === '') { verb = 'get'; }
return $.trim(verb.toString().toLowerCase());
},
_checkFormSubmission: function(form) {
var $form, path, verb, params, returned;
this.trigger('check-form-submission', {form: form});
$form = $(form);
path = $form.attr('action') || '';
verb = this._getFormVerb($form);
if (this.debug) {
this.log('_checkFormSubmission', $form, path, verb);
}
if (verb === 'get') {
params = this._serializeFormParams($form);
if (params !== '') { path += '?' + params; }
this.setLocation(path);
returned = false;
} else {
params = $.extend({}, this._parseFormParams($form));
returned = this.runRoute(verb, path, params, form.get(0));
}
return (typeof returned == 'undefined') ? false : returned;
},
_serializeFormParams: function($form) {
var queryString = "",
fields = $form.serializeArray(),
i;
if (fields.length > 0) {
queryString = this._encodeFormPair(fields[0].name, fields[0].value);
for (i = 1; i < fields.length; i++) {
queryString = queryString + "&" + this._encodeFormPair(fields[i].name, fields[i].value);
}
}
return queryString;
},
_encodeFormPair: function(name, value){
return _encode(name) + "=" + _encode(value);
},
_parseFormParams: function($form) {
var params = {},
form_fields = $form.serializeArray(),
i;
for (i = 0; i < form_fields.length; i++) {
params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value);
}
return params;
},
_parseQueryString: function(path) {
var params = {}, parts, pairs, pair, i;
parts = path.match(QUERY_STRING_MATCHER);
if (parts && parts[1]) {
pairs = parts[1].split('&');
for (i = 0; i < pairs.length; i++) {
pair = pairs[i].split('=');
params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1] || ""));
}
}
return params;
},
_parseParamPair: function(params, key, value) {
if (typeof params[key] !== 'undefined') {
if (_isArray(params[key])) {
params[key].push(value);
} else {
params[key] = [params[key], value];
}
} else {
params[key] = value;
}
return params;
},
_listen: function(name, callback) {
return this.$element().bind([name, this.eventNamespace()].join('.'), callback);
},
_unlisten: function(name, callback) {
return this.$element().unbind([name, this.eventNamespace()].join('.'), callback);
}
});
// `Sammy.RenderContext` is an object that makes sequential template loading,
// rendering and interpolation seamless even when dealing with asynchronous
// operations.
//
// `RenderContext` objects are not usually created directly, rather they are
// instantiated from an `Sammy.EventContext` by using `render()`, `load()` or
// `partial()` which all return `RenderContext` objects.
//
// `RenderContext` methods always returns a modified `RenderContext`
// for chaining (like jQuery itself).
//
// The core magic is in the `then()` method which puts the callback passed as
// an argument into a queue to be executed once the previous callback is complete.
// All the methods of `RenderContext` are wrapped in `then()` which allows you
// to queue up methods by chaining, but maintaining a guaranteed execution order
// even with remote calls to fetch templates.
//
Sammy.RenderContext = function(event_context) {
this.event_context = event_context;
this.callbacks = [];
this.previous_content = null;
this.content = null;
this.next_engine = false;
this.waiting = false;
};
Sammy.RenderContext.prototype = $.extend({}, Sammy.Object.prototype, {
// The "core" of the `RenderContext` object, adds the `callback` to the
// queue. If the context is `waiting` (meaning an async operation is happening)
// then the callback will be executed in order, once the other operations are
// complete. If there is no currently executing operation, the `callback`
// is executed immediately.
//
// The value returned from the callback is stored in `content` for the
// subsequent operation. If you return `false`, the queue will pause, and
// the next callback in the queue will not be executed until `next()` is
// called. This allows for the guaranteed order of execution while working
// with async operations.
//
// If then() is passed a string instead of a function, the string is looked
// up as a helper method on the event context.
//
// ### Example
//
// this.get('#/', function() {
// // initialize the RenderContext
// // Even though `load()` executes async, the next `then()`
// // wont execute until the load finishes
// this.load('myfile.txt')
// .then(function(content) {
// // the first argument to then is the content of the
// // prev operation
// $('#main').html(content);
// });
// });
//
then: function(callback) {
if (!_isFunction(callback)) {
// if a string is passed to then, assume we want to call
// a helper on the event context in its context
if (typeof callback === 'string' && callback in this.event_context) {
var helper = this.event_context[callback];
callback = function(content) {
return helper.apply(this.event_context, [content]);
};
} else {
return this;
}
}
var context = this;
if (this.waiting) {
this.callbacks.push(callback);
} else {
this.wait();
window.setTimeout(function() {
var returned = callback.apply(context, [context.content, context.previous_content]);
if (returned !== false) {
context.next(returned);
}
}, 0);
}
return this;
},
// Pause the `RenderContext` queue. Combined with `next()` allows for async
// operations.
//
// ### Example
//
// this.get('#/', function() {
// this.load('mytext.json')
// .then(function(content) {
// var context = this,
// data = JSON.parse(content);
// // pause execution
// context.wait();
// // post to a url
// $.post(data.url, {}, function(response) {
// context.next(JSON.parse(response));
// });
// })
// .then(function(data) {
// // data is json from the previous post
// $('#message').text(data.status);
// });
// });
wait: function() {
this.waiting = true;
},
// Resume the queue, setting `content` to be used in the next operation.
// See `wait()` for an example.
next: function(content) {
this.waiting = false;
if (typeof content !== 'undefined') {
this.previous_content = this.content;
this.content = content;
}
if (this.callbacks.length > 0) {
this.then(this.callbacks.shift());
}
},
// Load a template into the context.
// The `location` can either be a string specifying the remote path to the
// file, a jQuery object, or a DOM element.
//
// No interpolation happens by default, the content is stored in
// `content`.
//
// In the case of a path, unless the option `{cache: false}` is passed the
// data is stored in the app's `templateCache()`.
//
// If a jQuery or DOM object is passed the `innerHTML` of the node is pulled in.
// This is useful for nesting templates as part of the initial page load wrapped
// in invisible elements or `<script>` tags. With template paths, the template
// engine is looked up by the extension. For DOM/jQuery embedded templates,
// this isnt possible, so there are a couple of options:
//
// * pass an `{engine:}` option.
// * define the engine in the `data-engine` attribute of the passed node.
// * just store the raw template data and use `interpolate()` manually
//
// If a `callback` is passed it is executed after the template load.
load: function(location, options, callback) {
var context = this;
return this.then(function() {
var should_cache, cached, is_json, location_array;
if (_isFunction(options)) {
callback = options;
options = {};
} else {
options = $.extend({}, options);
}
if (callback) { this.then(callback); }
if (typeof location === 'string') {
// it's a path
is_json = (location.match(/\.json$/) || options.json);
should_cache = is_json ? options.cache === true : options.cache !== false;
context.next_engine = context.event_context.engineFor(location);
delete options.cache;
delete options.json;
if (options.engine) {
context.next_engine = options.engine;
delete options.engine;
}
if (should_cache && (cached = this.event_context.app.templateCache(location))) {
return cached;
}
this.wait();
$.ajax($.extend({
url: location,
data: {},
dataType: is_json ? 'json' : 'text',
type: 'get',
success: function(data) {
if (should_cache) {
context.event_context.app.templateCache(location, data);
}
context.next(data);
}
}, options));
return false;
} else {
// it's a dom/jQuery
if (location.nodeType) {
return location.innerHTML;
}
if (location.selector) {
// it's a jQuery
context.next_engine = location.attr('data-engine');
if (options.clone === false) {
return location.remove()[0].innerHTML.toString();
} else {
return location[0].innerHTML.toString();
}
}
}
});
},
// Load partials
//
// ### Example
//
// this.loadPartials({mypartial: '/path/to/partial'});
//
loadPartials: function(partials) {
var name;
if(partials) {
this.partials = this.partials || {};
for(name in partials) {
(function(context, name) {
context.load(partials[name])
.then(function(template) {
this.partials[name] = template;
});
})(this, name);
}
}
return this;
},
// `load()` a template and then `interpolate()` it with data.
//
// can be called with multiple different signatures:
//
// this.render(callback);
// this.render('/location');
// this.render('/location', {some: data});
// this.render('/location', callback);
// this.render('/location', {some: data}, callback);
// this.render('/location', {some: data}, {my: partials});
// this.render('/location', callback, {my: partials});
// this.render('/location', {some: data}, callback, {my: partials});
//
// ### Example
//
// this.get('#/', function() {
// this.render('mytemplate.template', {name: 'test'});
// });
//
render: function(location, data, callback, partials) {
if (_isFunction(location) && !data) {
// invoked as render(callback)
return this.then(location);
} else {
if(_isFunction(data)) {
// invoked as render(location, callback, [partials])
partials = callback;
callback = data;
data = null;
} else if(callback && !_isFunction(callback)) {
// invoked as render(location, data, partials)
partials = callback;
callback = null;
}
return this.loadPartials(partials)
.load(location)
.interpolate(data, location)
.then(callback);
}
},
// `render()` the `location` with `data` and then `swap()` the
// app's `$element` with the rendered content.
partial: function(location, data, callback, partials) {
if (_isFunction(callback)) {
// invoked as partial(location, data, callback, [partials])
return this.render(location, data, partials).swap(callback);
} else if (_isFunction(data)) {
// invoked as partial(location, callback, [partials])
return this.render(location, {}, callback).swap(data);
} else {
// invoked as partial(location, data, [partials])
return this.render(location, data, callback).swap();
}
},
// defers the call of function to occur in order of the render queue.
// The function can accept any number of arguments as long as the last
// argument is a callback function. This is useful for putting arbitrary
// asynchronous functions into the queue. The content passed to the
// callback is passed as `content` to the next item in the queue.
//
// ### Example
//
// this.send($.getJSON, '/app.json')
// .then(function(json) {
// $('#message).text(json['message']);
// });
//
//
send: function() {
var context = this,
args = _makeArray(arguments),
fun = args.shift();
if (_isArray(args[0])) { args = args[0]; }
return this.then(function(content) {
args.push(function(response) { context.next(response); });
context.wait();
fun.apply(fun, args);
return false;
});
},
// iterates over an array, applying the callback for each item item. the
// callback takes the same style of arguments as `jQuery.each()` (index, item).
// The return value of each callback is collected as a single string and stored
// as `content` to be used in the next iteration of the `RenderContext`.
collect: function(array, callback, now) {
var context = this;
var coll = function() {
if (_isFunction(array)) {
callback = array;
array = this.content;
}
var contents = [], doms = false;
$.each(array, function(i, item) {
var returned = callback.apply(context, [i, item]);
if (returned.jquery && returned.length == 1) {
returned = returned[0];
doms = true;
}
contents.push(returned);
return returned;
});
return doms ? contents : contents.join('');
};
return now ? coll() : this.then(coll);
},
// loads a template, and then interpolates it for each item in the `data`
// array. If a callback is passed, it will call the callback with each
// item in the array _after_ interpolation
renderEach: function(location, name, data, callback) {
if (_isArray(name)) {
callback = data;
data = name;
name = null;
}
return this.load(location).then(function(content) {
var rctx = this;
if (!data) {
data = _isArray(this.previous_content) ? this.previous_content : [];
}
if (callback) {
$.each(data, function(i, value) {
var idata = {}, engine = this.next_engine || location;
if (name) {
idata[name] = value;
} else {
idata = value;
}
callback(value, rctx.event_context.interpolate(content, idata, engine));
});
} else {
return this.collect(data, function(i, value) {
var idata = {}, engine = this.next_engine || location;
if (name) {
idata[name] = value;
} else {
idata = value;
}
return this.event_context.interpolate(content, idata, engine);
}, true);
}
});
},
// uses the previous loaded `content` and the `data` object to interpolate
// a template. `engine` defines the templating/interpolation method/engine
// that should be used. If `engine` is not passed, the `next_engine` is
// used. If `retain` is `true`, the final interpolated data is appended to
// the `previous_content` instead of just replacing it.
interpolate: function(data, engine, retain) {
var context = this;
return this.then(function(content, prev) {
if (!data && prev) { data = prev; }
if (this.next_engine) {
engine = this.next_engine;
this.next_engine = false;
}
var rendered = context.event_context.interpolate(content, data, engine, this.partials);
return retain ? prev + rendered : rendered;
});
},
// Swap the return contents ensuring order. See `Application#swap`
swap: function(callback) {
return this.then(function(content) {
this.event_context.swap(content, callback);
return content;
}).trigger('changed', {});
},
// Same usage as `jQuery.fn.appendTo()` but uses `then()` to ensure order
appendTo: function(selector) {
return this.then(function(content) {
$(selector).append(content);
}).trigger('changed', {});
},
// Same usage as `jQuery.fn.prependTo()` but uses `then()` to ensure order
prependTo: function(selector) {
return this.then(function(content) {
$(selector).prepend(content);
}).trigger('changed', {});
},
// Replaces the `$(selector)` using `html()` with the previously loaded
// `content`
replace: function(selector) {
return this.then(function(content) {
$(selector).html(content);
}).trigger('changed', {});
},
// trigger the event in the order of the event context. Same semantics
// as `Sammy.EventContext#trigger()`. If data is omitted, `content`
// is sent as `{content: content}`
trigger: function(name, data) {
return this.then(function(content) {
if (typeof data == 'undefined') { data = {content: content}; }
this.event_context.trigger(name, data);
return content;
});
}
});
// `Sammy.EventContext` objects are created every time a route is run or a
// bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext`
// This within these callbacks the special methods of `EventContext` are available.
//
// ### Example
//
// $.sammy(function() {
// // The context here is this Sammy.Application
// this.get('#/:name', function() {
// // The context here is a new Sammy.EventContext
// if (this.params['name'] == 'sammy') {
// this.partial('name.html.erb', {name: 'Sammy'});
// } else {
// this.redirect('#/somewhere-else')
// }
// });
// });
//
// Initialize a new EventContext
//
// ### Arguments
//
// * `app` The `Sammy.Application` this event is called within.
// * `verb` The verb invoked to run this context/route.
// * `path` The string path invoked to run this context/route.
// * `params` An Object of optional params to pass to the context. Is converted
// to a `Sammy.Object`.
// * `target` a DOM element that the event that holds this context originates
// from. For post, put and del routes, this is the form element that triggered
// the route.
//
Sammy.EventContext = function(app, verb, path, params, target) {
this.app = app;
this.verb = verb;
this.path = path;
this.params = new Sammy.Object(params);
this.target = target;
};
Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, {
// A shortcut to the app's `$element()`
$element: function() {
return this.app.$element(_makeArray(arguments).shift());
},
// Look up a templating engine within the current app and context.
// `engine` can be one of the following:
//
// * a function: should conform to `function(content, data) { return interpolated; }`
// * a template path: 'template.ejs', looks up the extension to match to
// the `ejs()` helper
// * a string referring to the helper: "mustache" => `mustache()`
//
// If no engine is found, use the app's default `template_engine`
//
engineFor: function(engine) {
var context = this, engine_match;
// if path is actually an engine function just return it
if (_isFunction(engine)) { return engine; }
// lookup engine name by path extension
engine = (engine || context.app.template_engine).toString();
if ((engine_match = engine.match(/\.([^\.\?\#]+)$/))) {
engine = engine_match[1];
}
// set the engine to the default template engine if no match is found
if (engine && _isFunction(context[engine])) {
return context[engine];
}
if (context.app.template_engine) {
return this.engineFor(context.app.template_engine);
}
return function(content, data) { return content; };
},
// using the template `engine` found with `engineFor()`, interpolate the
// `data` into `content`
interpolate: function(content, data, engine, partials) {
return this.engineFor(engine).apply(this, [content, data, partials]);
},
// Create and return a `Sammy.RenderContext` calling `render()` on it.
// Loads the template and interpolate the data, however does not actual
// place it in the DOM.
//
// ### Example
//
// // mytemplate.mustache <div class="name">{{name}}</div>
// render('mytemplate.mustache', {name: 'quirkey'});
// // sets the `content` to <div class="name">quirkey</div>
// render('mytemplate.mustache', {name: 'quirkey'})
// .appendTo('ul');
// // appends the rendered content to $('ul')
//
render: function(location, data, callback, partials) {
return new Sammy.RenderContext(this).render(location, data, callback, partials);
},
// Create and return a `Sammy.RenderContext` calling `renderEach()` on it.
// Loads the template and interpolates the data for each item,
// however does not actual place it in the DOM.
//
// ### Example
//
// // mytemplate.mustache <div class="name">{{name}}</div>
// renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}])
// // sets the `content` to <div class="name">quirkey</div><div class="name">endor</div>
// renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}]).appendTo('ul');
// // appends the rendered content to $('ul')
//
renderEach: function(location, name, data, callback) {
return new Sammy.RenderContext(this).renderEach(location, name, data, callback);
},
// create a new `Sammy.RenderContext` calling `load()` with `location` and
// `options`. Called without interpolation or placement, this allows for
// preloading/caching the templates.
load: function(location, options, callback) {
return new Sammy.RenderContext(this).load(location, options, callback);
},
// create a new `Sammy.RenderContext` calling `loadPartials()` with `partials`.
loadPartials: function(partials) {
return new Sammy.RenderContext(this).loadPartials(partials);
},
// `render()` the `location` with `data` and then `swap()` the
// app's `$element` with the rendered content.
partial: function(location, data, callback, partials) {
return new Sammy.RenderContext(this).partial(location, data, callback, partials);
},
// create a new `Sammy.RenderContext` calling `send()` with an arbitrary
// function
send: function() {
var rctx = new Sammy.RenderContext(this);
return rctx.send.apply(rctx, arguments);
},
// Changes the location of the current window. If `to` begins with
// '#' it only changes the document's hash. If passed more than 1 argument
// redirect will join them together with forward slashes.
//
// ### Example
//
// redirect('#/other/route');
// // equivalent to
// redirect('#', 'other', 'route');
//
redirect: function() {
var to, args = _makeArray(arguments),
current_location = this.app.getLocation(),
l = args.length;
if (l > 1) {
var i = 0, paths = [], pairs = [], params = {}, has_params = false;
for (; i < l; i++) {
if (typeof args[i] == 'string') {
paths.push(args[i]);
} else {
$.extend(params, args[i]);
has_params = true;
}
}
to = paths.join('/');
if (has_params) {
for (var k in params) {
pairs.push(this.app._encodeFormPair(k, params[k]));
}
to += '?' + pairs.join('&');
}
} else {
to = args[0];
}
this.trigger('redirect', {to: to});
this.app.last_location = [this.verb, this.path];
this.app.setLocation(to);
if (new RegExp(to).test(current_location)) {
this.app.trigger('location-changed');
}
},
// Triggers events on `app` within the current context.
trigger: function(name, data) {
if (typeof data == 'undefined') { data = {}; }
if (!data.context) { data.context = this; }
return this.app.trigger(name, data);
},
// A shortcut to app's `eventNamespace()`
eventNamespace: function() {
return this.app.eventNamespace();
},
// A shortcut to app's `swap()`
swap: function(contents, callback) {
return this.app.swap(contents, callback);
},
// Raises a possible `notFound()` error for the current path.
notFound: function() {
return this.app.notFound(this.verb, this.path);
},
// Default JSON parsing uses jQuery's `parseJSON()`. Include `Sammy.JSON`
// plugin for the more conformant "crockford special".
json: function(string) {
return $.parseJSON(string);
},
// //=> Sammy.EventContext: get #/ {}
toString: function() {
return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' ');
}
});
return Sammy;
});
})(jQuery, window);
...@@ -11,11 +11,6 @@ ...@@ -11,11 +11,6 @@
// adapted from: http://ejohn.org/blog/javascript-micro-templating/ // adapted from: http://ejohn.org/blog/javascript-micro-templating/
// originally $.srender by Greg Borenstein http://ideasfordozens.com in Feb 2009 // originally $.srender by Greg Borenstein http://ideasfordozens.com in Feb 2009
// modified for Sammy by Aaron Quint for caching templates by name // modified for Sammy by Aaron Quint for caching templates by name
// Backport of escapeHTML from sammy.js 0.7
var _escapeHTML = function(s) {
return String(s).replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
};
var srender_cache = {}; var srender_cache = {};
var srender = function(name, template, data, options) { var srender = function(name, template, data, options) {
var fn, escaped_string; var fn, escaped_string;
...@@ -137,7 +132,7 @@ ...@@ -137,7 +132,7 @@
if (typeof options == 'undefined' && typeof name == 'object') { if (typeof options == 'undefined' && typeof name == 'object') {
options = name; name = template; options = name; name = template;
} }
return srender(name, template, $.extend({h: _escapeHTML}, this, data), options); return srender(name, template, $.extend({}, this, data), options);
}; };
// set the default method name/extension // set the default method name/extension
......
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
color: inherit;
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #eaeaea url('bg.png');
color: #4d4d4d;
width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
#todoapp {
background: #fff;
background: rgba(255, 255, 255, 0.9);
margin: 130px 0 40px 0;
border: 1px solid #ccc;
position: relative;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.15);
}
#todoapp:before {
content: '';
border-left: 1px solid #f5d6d6;
border-right: 1px solid #f5d6d6;
width: 2px;
position: absolute;
top: 0;
left: 40px;
height: 100%;
}
#todoapp input::-webkit-input-placeholder {
font-style: italic;
}
#todoapp input:-moz-placeholder {
font-style: italic;
color: #a9a9a9;
}
#todoapp h1 {
position: absolute;
top: -120px;
width: 100%;
font-size: 70px;
font-weight: bold;
text-align: center;
color: #b3b3b3;
color: rgba(255, 255, 255, 0.3);
text-shadow: -1px -1px rgba(0, 0, 0, 0.2);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
-ms-text-rendering: optimizeLegibility;
-o-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
#header {
padding-top: 15px;
border-radius: inherit;
}
#header:before {
content: '';
position: absolute;
top: 0;
right: 0;
left: 0;
height: 15px;
z-index: 2;
border-bottom: 1px solid #6c615c;
background: #8d7d77;
background: -webkit-gradient(linear, left top, left bottom, from(rgba(132, 110, 100, 0.8)),to(rgba(101, 84, 76, 0.8)));
background: -webkit-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -moz-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -o-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: -ms-linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
background: linear-gradient(top, rgba(132, 110, 100, 0.8), rgba(101, 84, 76, 0.8));
filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,StartColorStr='#9d8b83', EndColorStr='#847670');
border-top-left-radius: 1px;
border-top-right-radius: 1px;
}
#new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
line-height: 1.4em;
border: 0;
outline: none;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
-ms-font-smoothing: antialiased;
-o-font-smoothing: antialiased;
font-smoothing: antialiased;
}
#new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.02);
z-index: 2;
box-shadow: none;
}
#main {
position: relative;
z-index: 2;
border-top: 1px dotted #adadad;
}
label[for='toggle-all'] {
display: none;
}
#toggle-all {
position: absolute;
top: -42px;
left: -4px;
width: 40px;
text-align: center;
border: none; /* Mobile Safari */
}
#toggle-all:before {
content: '»';
font-size: 28px;
color: #d9d9d9;
padding: 0 25px 7px;
}
#toggle-all:checked:before {
color: #737373;
}
#todo-list {
margin: 0;
padding: 0;
list-style: none;
}
#todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px dotted #ccc;
}
#todo-list li:last-child {
border-bottom: none;
}
#todo-list li.editing {
border-bottom: none;
padding: 0;
}
#todo-list li.editing .edit {
display: block;
width: 506px;
padding: 13px 17px 12px 17px;
margin: 0 0 0 43px;
}
#todo-list li.editing .view {
display: none;
}
#todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
/*-moz-appearance: none;*/
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
#todo-list li .toggle:after {
content: '✔';
line-height: 43px; /* 40 + a couple of pixels visual adjustment */
font-size: 20px;
color: #d9d9d9;
text-shadow: 0 -1px 0 #bfbfbf;
}
#todo-list li .toggle:checked:after {
color: #85ada7;
text-shadow: 0 1px 0 #669991;
bottom: 1px;
position: relative;
}
#todo-list li label {
word-break: break-word;
padding: 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
-webkit-transition: color 0.4s;
-moz-transition: color 0.4s;
-ms-transition: color 0.4s;
-o-transition: color 0.4s;
transition: color 0.4s;
}
#todo-list li.completed label {
color: #a9a9a9;
text-decoration: line-through;
}
#todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 22px;
color: #a88a8a;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-ms-transition: all 0.2s;
-o-transition: all 0.2s;
transition: all 0.2s;
}
#todo-list li .destroy:hover {
text-shadow: 0 0 1px #000,
0 0 10px rgba(199, 107, 107, 0.8);
-webkit-transform: scale(1.3);
-moz-transform: scale(1.3);
-ms-transform: scale(1.3);
-o-transform: scale(1.3);
transform: scale(1.3);
}
#todo-list li .destroy:after {
content: '✖';
}
#todo-list li:hover .destroy {
display: block;
}
#todo-list li .edit {
display: none;
}
#todo-list li.editing:last-child {
margin-bottom: -1px;
}
#footer {
color: #777;
padding: 0 15px;
position: absolute;
right: 0;
bottom: -31px;
left: 0;
height: 20px;
z-index: 1;
text-align: center;
}
#footer:before {
content: '';
position: absolute;
right: 0;
bottom: 31px;
left: 0;
height: 50px;
z-index: -1;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3),
0 6px 0 -3px rgba(255, 255, 255, 0.8),
0 7px 1px -3px rgba(0, 0, 0, 0.3),
0 43px 0 -6px rgba(255, 255, 255, 0.8),
0 44px 2px -6px rgba(0, 0, 0, 0.2);
}
#todo-count {
float: left;
text-align: left;
}
#filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
#filters li {
display: inline;
}
#filters li a {
color: #83756f;
margin: 2px;
text-decoration: none;
}
#filters li a.selected {
font-weight: bold;
}
#clear-completed {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
background: rgba(0, 0, 0, 0.1);
font-size: 11px;
padding: 0 10px;
border-radius: 3px;
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.2);
}
#clear-completed:hover {
background: rgba(0, 0, 0, 0.15);
box-shadow: 0 -1px 0 0 rgba(0, 0, 0, 0.3);
}
#info {
margin: 65px auto 0;
color: #a6a6a6;
font-size: 12px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.7);
text-align: center;
}
#info a {
color: inherit;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox and Opera
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
#toggle-all,
#todo-list li .toggle {
background: none;
}
#todo-list li .toggle {
height: 40px;
}
#toggle-all {
top: -56px;
left: -15px;
width: 65px;
height: 41px;
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
appearance: none;
}
}
.hidden{
display:none;
}
(function () {
'use strict';
if (location.hostname === 'todomvc.com') {
window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
}
function getSourcePath() {
// If accessed via addyosmani.github.com/todomvc/, strip the project
// path.
if (location.hostname.indexOf('github.com') > 0) {
return location.pathname.replace(/todomvc\//, '');
}
return location.pathname;
}
function appendSourceLink() {
var sourceLink = document.createElement('a');
var paragraph = document.createElement('p');
var footer = document.getElementById('info');
var urlBase = 'https://github.com/addyosmani/todomvc/tree/gh-pages';
if (footer) {
sourceLink.href = urlBase + getSourcePath();
sourceLink.appendChild(document.createTextNode('Check out the source'));
paragraph.appendChild(sourceLink);
footer.appendChild(paragraph);
}
}
function redirect() {
if (location.hostname === 'addyosmani.github.com') {
location.href = location.href.replace('addyosmani.github.com/todomvc',
'todomvc.com');
}
}
appendSourceLink();
redirect();
})();
body { margin: 0; padding: 0; font-family: Helvetica; color: #444; }
#surface { position: relative; margin: 0 auto; width: 600px; }
h1 { position: relative; top: 18px; z-index: 2; margin: 0; padding: 0; width: 100%; height: 1.2em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 25px; font-weight: normal; }
#lists { position: absolute; top: 50px; left: 400px; z-index: 2; }
dl { margin: 0; padding: 0; color: #555; }
dt { margin: 0 0 5px 0; padding: 0; font-size: 20px; font-weight: normal; }
dd { margin: 0 0 5px 15px; padding: 0; font-size: 17px; cursor: pointer; }
#page { float: left; position: relative; z-index: 1; width: 400px; height: 600px; }
#page { }
h2 { position: absolute; top: 56px; left: 77px; margin: 0; font-size: 30px; width: 275px; height: 1.2em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: normal; }
/*ul { position: absolute; top: 116px; left: 80px; margin: 0; padding: 0; width: 275px; list-style: none; }*/
li { position: relative; margin: 0 0 0 25px; padding: 0; font-size: 20px; line-height: 27px; }
p { position: absolute; top: 116px; left: 80px; margin: 0; padding: 0; width: 275px; font-size: 20px; line-height: 27px; }
[contenteditable]:hover { outline: 1px dotted #999; }
.new { opacity: .25; cursor: pointer; }
.new:hover { opacity: .75; }
.trashcan { position: absolute; top: 63px; left: 57px; width: 25px; height: 25px; cursor: pointer; background: url(destroy.png) no-repeat; }
.trashcan:hover { opacity: .75; }
li .trashcan { float: right;
left: 95%;
top: 15px; }
#page:hover .trashcan { display: inline-block; }
/*todos*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
}
body {
line-height: 1;
color: black;
background: white;
}
ol, ul {
list-style: none;
}
a img {
border: none;
}
html {
background: #eeeeee;
}
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.4em;
background: #eeeeee;
color: #333333;
}
#todoapp {
width: 480px;
margin: 0 auto 40px;
background: white;
padding: 20px;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0 5px 6px 0;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 5px 6px 0;
-o-box-shadow: rgba(0, 0, 0, 0.2) 0 5px 6px 0;
box-shadow: rgba(0, 0, 0, 0.2) 0 5px 6px 0;
-moz-border-radius: 0 0 5px 5px;
-o-border-radius: 0 0 5px 5px;
-webkit-border-radius: 0 0 5px 5px;
border-radius: 0 0 5px 5px;
}
#todoapp h1 {
font-size: 36px;
font-weight: bold;
text-align: center;
padding: 20px 0 30px 0;
line-height: 1;
}
#create-todo {
position: relative;
}
#create-todo input {
width: 466px;
font-size: 24px;
font-family: inherit;
line-height: 1.4em;
border: 0;
outline: none;
padding: 6px;
border: 1px solid #999999;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
-o-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
}
#create-todo input::-webkit-input-placeholder {
font-style: italic;
}
#create-todo span {
position: absolute;
z-index: 999;
width: 170px;
left: 50%;
margin-left: -85px;
}
#todo-list {
margin-top: 10px;
}
#todo-list li {
padding: 12px 20px 11px 0;
position: relative;
font-size: 24px;
line-height: 1.1em;
border-bottom: 1px solid #cccccc;
}
#todo-list li:after {
content: "\0020";
display: block;
height: 0;
clear: both;
overflow: hidden;
visibility: hidden;
}
#todo-list li.editing {
padding: 0;
border-bottom: 0;
}
#todo-list .editing .display,
#todo-list .edit {
display: none;
}
#todo-list .editing .edit {
display: block;
}
#todo-list .editing input {
width: 444px;
font-size: 24px;
font-family: inherit;
margin: 0;
line-height: 1.6em;
border: 0;
outline: none;
padding: 10px 7px 0px 27px;
border: 1px solid #999999;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
-o-box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
box-shadow: rgba(0, 0, 0, 0.2) 0 1px 2px 0 inset;
}
#todo-list .check {
position: relative;
top: 9px;
margin: 0 10px 0 7px;
float: left;
}
#todo-list .done {
text-decoration: line-through;
color: #777777;
}
#todo-list .todo-destroy {
position: absolute;
right: 5px;
top: 14px;
display: none;
cursor: pointer;
width: 20px;
height: 20px;
background: url(destroy.png) no-repeat 0 0;
}
#todo-list li:hover .todo-destroy {
display: block;
}
#todo-list .todo-destroy:hover {
background-position: 0 -20px;
}
#todo-stats {
*zoom: 1;
margin-top: 10px;
color: #777777;
}
#todo-stats:after {
content: "\0020";
display: block;
height: 0;
clear: both;
overflow: hidden;
visibility: hidden;
}
#todo-stats .todo-count {
float: left;
}
#todo-stats .todo-count .number {
font-weight: bold;
color: #333333;
}
#todo-stats .todo-clear {
float: right;
}
#todo-stats .todo-clear a {
color: #777777;
font-size: 12px;
}
#todo-stats .todo-clear a:visited {
color: #777777;
}
#todo-stats .todo-clear a:hover {
color: #336699;
}
#instructions {
width: 520px;
margin: 10px auto;
color: #777777;
text-shadow: rgba(255, 255, 255, 0.8) 0 1px 0;
text-align: center;
}
#instructions a {
color: #336699;
}
#credits {
width: 520px;
margin: 30px auto;
color: #999;
text-shadow: rgba(255, 255, 255, 0.8) 0 1px 0;
text-align: center;
}
#credits a {
color: #888;
}
/*
* François 'cahnory' Germain
*/
.ui-tooltip, .ui-tooltip-top, .ui-tooltip-right, .ui-tooltip-bottom, .ui-tooltip-left {
color:#ffffff;
cursor:normal;
display:-moz-inline-stack;
display:inline-block;
font-size:12px;
font-family:arial;
padding:.5em 1em;
position:relative;
text-align:center;
text-shadow:0 -1px 1px #111111;
-webkit-border-top-left-radius:4px ;
-webkit-border-top-right-radius:4px ;
-webkit-border-bottom-right-radius:4px ;
-webkit-border-bottom-left-radius:4px ;
-khtml-border-top-left-radius:4px ;
-khtml-border-top-right-radius:4px ;
-khtml-border-bottom-right-radius:4px ;
-khtml-border-bottom-left-radius:4px ;
-moz-border-radius-topleft:4px ;
-moz-border-radius-topright:4px ;
-moz-border-radius-bottomright:4px ;
-moz-border-radius-bottomleft:4px ;
border-top-left-radius:4px ;
border-top-right-radius:4px ;
border-bottom-right-radius:4px ;
border-bottom-left-radius:4px ;
-o-box-shadow:0 1px 2px #000000, inset 0 0 0 1px #222222, inset 0 2px #666666, inset 0 -2px 2px #444444;
-moz-box-shadow:0 1px 2px #000000, inset 0 0 0 1px #222222, inset 0 2px #666666, inset 0 -2px 2px #444444;
-khtml-box-shadow:0 1px 2px #000000, inset 0 0 0 1px #222222, inset 0 2px #666666, inset 0 -2px 2px #444444;
-webkit-box-shadow:0 1px 2px #000000, inset 0 0 0 1px #222222, inset 0 2px #666666, inset 0 -2px 2px #444444;
box-shadow:0 1px 2px #000000, inset 0 0 0 1px #222222, inset 0 2px #666666, inset 0 -2px 2px #444444;
background-color:#3b3b3b;
background-image:-moz-linear-gradient(top,#555555,#222222);
background-image:-webkit-gradient(linear,left top,left bottom,color-stop(0,#555555),color-stop(1,#222222));
filter:progid:DXImageTransform.Microsoft.gradient(startColorStr=#555555,EndColorStr=#222222);
-ms-filter:progid:DXImageTransform.Microsoft.gradient(startColorStr=#555555,EndColorStr=#222222);
}
.ui-tooltip:after, .ui-tooltip-top:after, .ui-tooltip-right:after, .ui-tooltip-bottom:after, .ui-tooltip-left:after {
content:"\25B8";
display:block;
font-size:2em;
height:0;
line-height:0;
position:absolute;
}
.ui-tooltip:after, .ui-tooltip-bottom:after {
color:#2a2a2a;
bottom:0;
left:1px;
text-align:center;
text-shadow:1px 0 2px #000000;
-o-transform:rotate(90deg);
-moz-transform:rotate(90deg);
-khtml-transform:rotate(90deg);
-webkit-transform:rotate(90deg);
width:100%;
}
.ui-tooltip-top:after {
bottom:auto;
color:#4f4f4f;
left:-2px;
top:0;
text-align:center;
text-shadow:none;
-o-transform:rotate(-90deg);
-moz-transform:rotate(-90deg);
-khtml-transform:rotate(-90deg);
-webkit-transform:rotate(-90deg);
width:100%;
}
.ui-tooltip-right:after {
color:#222222;
right:-0.375em;
top:50%;
margin-top:-.05em;
text-shadow:0 1px 2px #000000;
-o-transform:rotate(0);
-moz-transform:rotate(0);
-khtml-transform:rotate(0);
-webkit-transform:rotate(0);
}
.ui-tooltip-left:after {
color:#222222;
left:-0.375em;
top:50%;
margin-top:.1em;
text-shadow:0 -1px 2px #000000;
-o-transform:rotate(180deg);
-moz-transform:rotate(180deg);
-khtml-transform:rotate(180deg);
-webkit-transform:rotate(180deg);
}
/* new additions - cleanup required*/
/* line 109 */
#todoapp #todo-stats {
*zoom: 1;
margin-top: 10px;
color: #555555;
-moz-border-radius-bottomleft: 5px;
-webkit-border-bottom-left-radius: 5px;
-o-border-bottom-left-radius: 5px;
-ms-border-bottom-left-radius: 5px;
-khtml-border-bottom-left-radius: 5px;
border-bottom-left-radius: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-bottom-right-radius: 5px;
-o-border-bottom-right-radius: 5px;
-ms-border-bottom-right-radius: 5px;
-khtml-border-bottom-right-radius: 5px;
border-bottom-right-radius: 5px;
background: #f4fce8;
border-top: 1px solid #ededed;
padding: 0 20px;
line-height: 36px;
}
/* line 22, /opt/ree/lib/ruby/gems/1.8/gems/compass-0.10.5/frameworks/compass/stylesheets/compass/utilities/general/_clearfix.scss */
#todoapp #todo-stats:after {
content: "\0020";
display: block;
height: 0;
clear: both;
overflow: hidden;
visibility: hidden;
}
/* line 118 */
#todoapp #todo-stats .todo-count {
float: left;
}
/* line 120 */
#todoapp #todo-stats .todo-count .number {
font-weight: bold;
color: #555555;
}
/* line 123 */
#todoapp #todo-stats .todo-clear {
float: right;
}
/* line 125 */
#todoapp #todo-stats .todo-clear a {
display: block;
line-height: 20px;
text-decoration: none;
-moz-border-radius: 12px;
-webkit-border-radius: 12px;
-o-border-radius: 12px;
-ms-border-radius: 12px;
-khtml-border-radius: 12px;
border-radius: 12px;
background: rgba(0, 0, 0, 0.1);
color: #555555;
font-size: 11px;
margin-top: 8px;
padding: 0 10px 1px;
-moz-box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
-webkit-box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
-o-box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
box-shadow: rgba(0, 0, 0, 0.2) 0 -1px 0 0;
}
/* line 136 */
#todoapp #todo-stats .todo-clear a:hover, #todoapp #todo-stats .todo-clear a:focus {
background: rgba(0, 0, 0, 0.15);
-moz-box-shadow: rgba(0, 0, 0, 0.3) 0 -1px 0 0;
-webkit-box-shadow: rgba(0, 0, 0, 0.3) 0 -1px 0 0;
-o-box-shadow: rgba(0, 0, 0, 0.3) 0 -1px 0 0;
box-shadow: rgba(0, 0, 0, 0.3) 0 -1px 0 0;
}
/* line 139 */
#todoapp #todo-stats .todo-clear a:active {
position: relative;
top: 1px;
}
#todos { display:block}
<!doctype html> <!doctype html>
<html> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Sammy.js • TodoMVC</title> <title>Sammy.js • TodoMVC</title>
<link rel="stylesheet" href="css/app.css"> <link rel="stylesheet" href="components/todomvc-common/base.css">
<!--[if IE]>
<script src="../../../assets/ie.js"></script>
<![endif]-->
</head> </head>
<body> <body>
<div id="todoapp"> <section id="todoapp">
<div class="title"> <header id="header">
<h1>todos</h1> <h1>todos</h1>
</div> <input id="new-todo" placeholder="What needs to be done?" autofocus>
<div class="content"> </header>
<div id="create-todo"> <section id="main"></section>
<input id="new-todo" placeholder="What needs to be done?" type="text"> <footer id="footer"></footer>
</div> </section>
<div id="todos"> <footer id="info">
<ul id="todo-list"></ul> <p>Double-click to edit a todo</p>
</div> <p>Written by <a href="https://github.com/stephenplusplus">Stephen Sawchuk</a></p>
<div id="todo-stats"></div> <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</div> </footer>
</div> <script src="components/todomvc-common/base.js"></script>
<div id="credits"> <script src="components/jquery/jquery.js"></script>
This version by <script src="components/sammy/sammy.js"></script>
<br /> <script src="components/sammy/sammy.template.js"></script>
<a href="http://twitter.com/addyosmani">Addy Osmani</a>
<br />
based on some code by Brandon Aaron
</div>
<script src="../../../assets/base.js"></script>
<script src="../../../assets/jquery.min.js"></script>
<script src="js/lib/sammy.js"></script>
<script src="js/lib/sammy.template.js"></script>
<script src="js/lib/model.js"></script>
<script src="js/app.js"></script> <script src="js/app.js"></script>
<script src="js/controllers/TodoItem.js"></script>
<script src="js/controllers/TodoList.js"></script>
<script src="js/models/Todos.js"></script>
<script src="js/routes/active.js"></script>
<script src="js/routes/completed.js"></script>
<script src="js/routes/home.js"></script>
<script src="js/views/TodoItem.js"></script>
<script src="js/views/TodoList.js"></script>
</body> </body>
</html> </html>
(function($) { /*global Sammy, jQuery, TodoApp */
var ESCAPE_KEY = 13;
var app = $.sammy(function() {
this.use(Sammy.Template);
this.notFound = function(verb, path) {
this.runRoute('get', '#/404');
};
this.get('#/404', function() {
this.partial('templates/404.template', {}, function(html) {
$('#todo-list').html(html);
});
});
this.get('#/list/:id', function() {
var list = Lists.get(this.params['id']);
if (list) {
this.partial('templates/todolist.template', {
list: list,
todos: Todos.filter('listId', list.id)
}, function(html) {
$('#todo-list').html(html);
});
} else {
this.notFound();
}
});
// events
this.bind('run', function(e, data) {
var context = this;
var title = localStorage.getItem('title') || "Todos";
$('h1').text(title);
if(Lists._data.length <=0){
var list = Lists.create({ name: 'My new list' });
//app.trigger('updateLists');
}
$('#new-todo').keydown(function(e) {
if (e.keyCode == ESCAPE_KEY){
var todoContent = $(this).val();
var todo = Todos.create({ name: todoContent, done: false, listId: parseInt($('h2').attr('data-id'), 10) });
context.partial('templates/todo.template', todo, function(html) {
$('#todo-list').append(html);
});
$(this).val('');
}
});
$('.trashcan')
.live('click', function() {
var $this = $(this);
app.trigger('delete', {
type: $this.attr('data-type'),
id: $this.attr('data-id')
});
});
//new
$('.check')
.live('click', function() {
var $this = $(this),
$li = $this.parents('li').toggleClass('done'),
isDone = $li.is('.done');
app.trigger('mark' + (isDone ? 'Done' : 'Undone'), { id: $li.attr('data-id') });
});
(function (window, $) {
'use strict';
window.TodoApp = Sammy('#todoapp').use('Template');
$('[contenteditable]') TodoApp.notFound = function () {
.live('focus', function() { this.runRoute('get', '#/');
// store the current value };
$.data(this, 'prevValue', $(this).text());
})
.live('blur', function() {
var $this = $(this),
// grab the, likely, modified value
text = $.trim($this.text());
if (!text) {
// restore the previous value if text is empty
$this.text($.data(this, 'prevValue'));
} else {
if ($this.is('h1')) {
// it is the title
localStorage.setItem('title', text);
} else {
// save it
app.trigger('save', {
type: $this.attr('data-type'),
id: $this.attr('data-id'),
name: text
});
}
}
})
.live('keypress', function(event) {
// save on enter
if (event.which === 13) {
this.blur();
return false;
}
});
if (!localStorage.getItem('initialized')) {
// create first list and todo
var listId = Lists.create({
name: 'My first list'
}).id;
/*
Todos.create({
name: 'My first todo',
done: false,
listId: listId
});
*/
localStorage.setItem('initialized', 'yup');
this.redirect('#/list/'+listId);
} else {
var lastViewedOrFirstList = localStorage.getItem('lastviewed') || '#/list/' + Lists.first().id;
this.redirect(lastViewedOrFirstList);
}
});
/*save the route as the lastviewed item*/
this.bind('route-found', function(e, data) {
localStorage.setItem('lastviewed', document.location.hash);
});
this.bind('save', function(e, data) {
var model = data.type == 'todo' ? Todos : Lists;
model.update(data.id, { name: data.name });
});
/*marking the selected item as done*/
this.bind('markDone', function(e, data) {
Todos.update(data.id, { done: true });
});
/*mark the todo with the selected id as not done*/
this.bind('markUndone', function(e, data) {
Todos.update(data.id, { done: false });
});
this.bind('delete', function(e, data) {
//if (confirm('Are you sure you want to delete this ' + data.type + '?')) {
var model = data.type == 'list' ? Lists : Todos;
model.destroy(data.id);
if (data.type == 'list') {
var list = Lists.first();
if (list) {
this.redirect('#/list/'+list.id);
} else {
// create first list and todo
var listId = Lists.create({
name: 'Initial list'
}).id;
Todos.create({
name: 'A sample todo item',
done: false,
listId: listId
});
this.redirect('#/list/'+listId);
}
} else {
// delete the todo from the view
$('li[data-id=' + data.id + ']').remove();
}
});
$(function () {
TodoApp.run('#/');
}); });
})(window, jQuery);
// lists model
Lists = Object.create(Model);
Lists.name = 'lists-sammyjs';
Lists.init();
// todos model
Todos = Object.create(Model);
Todos.name = 'todos-sammyjs';
Todos.init();
$(function() { app.run(); });
})(jQuery);
/*global jQuery, TodoApp */
(function ($) {
'use strict';
var ESCAPE_KEY = 27;
var ENTER_KEY = 13;
var TodoItem = {
// `effectCause`
// i.e. "removeClick" = "a click to remove a todoItem"
removeClick: function () {
TodoApp.trigger('removeTodo', {
id: $(this).parents('li').data('id')
});
},
toggleClick: function () {
TodoApp.trigger('toggleTodoCompleted', {
id: $(this).parents('li').data('id')
});
},
editDblClick: function () {
$(this).parents('li').data('original-name', $(this).text());
TodoApp.trigger('editingTodo', {
id: $(this).parents('li').data('id')
});
},
editBlur: function () {
TodoApp.trigger('doneEditingTodo', {
id: $(this).parents('li').data('id'),
name: $.trim($(this).val())
});
},
editKeyup: function (e) {
if (e.which === ESCAPE_KEY) {
$(this).trigger('cancelEditingTodo', {
id: $(this).parents('li').data('id'),
name: $(this).parents('li').data('original-name')
});
}
if (e.which === ENTER_KEY) {
$(this).trigger('blur');
}
},
init: function () {
$('#todo-list')
.on('click', '.destroy', TodoItem.removeClick)
.on('click', '.toggle', TodoItem.toggleClick)
.on('dblclick', 'label', TodoItem.editDblClick)
.on('blur', '.edit', TodoItem.editBlur)
.on('keyup', '.edit', TodoItem.editKeyup);
}
};
TodoApp.bind('todoListRendered', TodoItem.init);
})(jQuery);
/*global jQuery, TodoApp */
(function ($) {
'use strict';
var ENTER_KEY = 13;
var TodoList = {
// `effectCause`
// i.e. "newKeydown" = "a keydown event to create a new Todo"
newKeydown: function (e) {
var name = $.trim($(this).val());
if (e.keyCode !== ENTER_KEY || !name) {
return;
}
TodoApp.trigger('saveTodo', {
name: name,
completed: false
});
$(this).val('');
},
toggleAllClick: (function () {
var flags = ['active', 'completed'];
var count = 1;
return function () {
TodoApp.trigger('toggleAllTodosCompleted', flags[count++ % 2]);
};
})(),
removeCompletedClick: function () {
TodoApp.trigger('removeCompletedTodos');
},
init: function () {
// The TodoApp has launched, let's bind our events.
$('#new-todo').on('keydown', TodoList.newKeydown);
$('#toggle-all').on('click', TodoList.toggleAllClick);
$('#footer').on('click', '#clear-completed', TodoList.removeCompletedClick);
}
};
TodoApp.bind('todoListRendered', TodoList.init);
})(jQuery);
Model={name:"model",init:function(){this._id=0;this._data=[];this._deserialize();return this},create:function(a,b){a.id=this._newId();var c=this._data[this._data.push(a)-1];!1!==b&&this.save();return this._clone(c)},first:function(){return this._clone(this._data[0])},last:function(){return this._clone(_data[this._data.length-1])},get:function(a){return this._clone(this._get(a))},getAll:function(){return this._clone(this._data)},filter:function(a,b){return this._clone(this._filter(a,b))},multiFilter:function(){return this._clone(this._multiFilter(filter))},
update:function(a,b,c){if(a=this._get(a)||!1)this._mixin(a,b),!1!==c&&this.save();return a},destroy:function(a,b){this._data.splice(this._indexOf(a),1);!1!==b&&this.save();return!0},destroyAll:function(a){this._data=[];!1!==a&&this.save();return!0},save:function(){this._serialize();return!0},_first:function(){return this._data[0]},_last:function(){return _data[this._data.length-1]},_get:function(a){return this._filter("id",a)[0]},_filter:function(a,b){var c=[],d,e,f="undefined"==typeof b;for(d in this._data)this._data.hasOwnProperty(d)&&
(e=this._data[d],(f||e[a]==b)&&c.push(e));return c},_multiFilter:function(a){var b=[],c,d,e;for(c in this._data)if(this._data.hasOwnProperty(c))for(d in e=this._data[c],a)a.hasOwnProperty(d)&&a[d]==e[d]&&b.push(e);return b},_indexOf:function(a){return this._data.indexOf(this._get(a))},_serialize:function(){localStorage[this.name]=JSON.stringify({prevId:this._id,data:this._data})},_deserialize:function(){var a=localStorage[this.name];a&&(a=JSON.parse(a),this._id=a.prevId,this._data=a.data)},_newId:function(){return this._id++},
_mixin:function(a,b){for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c])},_clone:function(a){var b=Object.prototype.toString.call(a),c=a;if("[object Object]"==b){var c={},d;for(d in a)a.hasOwnProperty(d)&&(c[d]=this._clone(a[d]))}else if("[object Array]"==b){c=[];b=0;for(d=a.length;b<d;b++)c[b]=this._clone(a[b])}return c}};"function"!==typeof Object.create&&(Object.create=function(a){function b(){}b.prototype=a;return new b});
\ No newline at end of file
(function(c){var e,l=/:([\w\d]+)/g,p=/\?([^#]*)$/,m=decodeURIComponent,h=function(a){return function(b,d){return this.route.apply(this,[a,b,d])}},q=[];e=function(){var a=c.makeArray(arguments),b,d;e.apps=e.apps||{};if(0===a.length||a[0]&&c.isFunction(a[0]))return e.apply(e,["body"].concat(a));if("string"==typeof(d=a.shift()))return b=e.apps[d]||new e.Application,b.element_selector=d,0<a.length&&c.each(a,function(a,d){b.use(d)}),b.element_selector!=d&&delete e.apps[d],e.apps[b.element_selector]=b};
e.VERSION="0.5.1";e.addLogger=function(a){q.push(a)};e.log=function(){var a=c.makeArray(arguments);a.unshift("["+Date()+"]");c.each(q,function(b,d){d.apply(e,a)})};"undefined"!=typeof window.console?c.isFunction(console.log.apply)?e.addLogger(function(){window.console.log.apply(console,arguments)}):e.addLogger(function(){window.console.log(arguments)}):"undefined"!=typeof console&&e.addLogger(function(){console.log.apply(console,arguments)});e.Object=function(a){return c.extend(this,a||{})};c.extend(e.Object.prototype,
{toHash:function(){var a={};c.each(this,function(b,d){c.isFunction(d)||(a[b]=d)});return a},toHTML:function(){var a="";c.each(this,function(b,d){c.isFunction(d)||(a+="<strong>"+b+"</strong> "+d+"<br />")});return a},uuid:function(){if("undefined"==typeof this._uuid||!this._uuid)this._uuid=(new Date).getTime()+"-"+parseInt(1E3*Math.random(),10);return this._uuid},keys:function(a){var b=[],d;for(d in this)(!c.isFunction(this[d])||!a)&&b.push(d);return b},has:function(a){return this[a]&&""!=c.trim(this[a].toString())},
join:function(){var a=c.makeArray(arguments),b=a.shift();return a.join(b)},log:function(){e.log.apply(e,arguments)},toString:function(a){var b=[];c.each(this,function(d,j){(!c.isFunction(j)||a)&&b.push('"'+d+'": '+j.toString())});return"Sammy.Object: {"+b.join(",")+"}"}});e.HashLocationProxy=function(a,b){this.app=a;"onhashchange"in window?(e.log("native hash change exists, using"),this.is_native=!0):(e.log("no native hash change, falling back to polling"),this.is_native=!1,this._startPolling(b))};
e.HashLocationProxy.prototype={bind:function(){var a=this.app;c(window).bind("hashchange."+this.app.eventNamespace(),function(){a.trigger("location-changed")})},unbind:function(){c(window).die("hashchange."+this.app.eventNamespace())},getLocation:function(){var a=window.location.toString().match(/^[^#]*(#.+)$/);return a?a[1]:""},setLocation:function(a){return window.location=a},_startPolling:function(a){var b=this;if(!e.HashLocationProxy._interval){a||(a=10);var d=function(){current_location=b.getLocation();
(!e.HashLocationProxy._last_location||current_location!=e.HashLocationProxy._last_location)&&setTimeout(function(){c(window).trigger("hashchange")},1);e.HashLocationProxy._last_location=current_location};d();e.HashLocationProxy._interval=setInterval(d,a);c(window).bind("beforeunload",function(){clearInterval(e.HashLocationProxy._interval)})}}};e.DataLocationProxy=function(a,b){this.app=a;this.data_name=b||"sammy-location"};e.DataLocationProxy.prototype={bind:function(){var a=this;this.app.$element().bind("setData",
function(b,d){d==a.data_name&&a.app.trigger("location-changed")})},unbind:function(){this.app.$element().die("setData")},getLocation:function(){return this.app.$element().data(this.data_name)},setLocation:function(a){return this.app.$element().data(this.data_name,a)}};e.Application=function(a){var b=this;this.routes={};this.listeners=new e.Object({});this.arounds=[];this.befores=[];this.namespace=this.uuid();this.context_prototype=function(){e.EventContext.apply(this,arguments)};this.context_prototype.prototype=
new e.EventContext;c.isFunction(a)&&a.apply(this,[this]);this.location_proxy||(this.location_proxy=new e.HashLocationProxy(b,this.run_interval_every));this.debug&&this.bindToAllEvents(function(a,c){b.log(b.toString(),a.cleaned_type,c||{})})};e.Application.prototype=c.extend({},e.Object.prototype,{ROUTE_VERBS:["get","post","put","delete"],APP_EVENTS:"run unload lookup-route run-route route-found event-context-before event-context-after changed error check-form-submission redirect".split(" "),_last_route:null,
_running:!1,element_selector:"body",debug:!1,raise_errors:!1,run_interval_every:50,location_proxy:null,template_engine:null,toString:function(){return"Sammy.Application:"+this.element_selector},$element:function(){return c(this.element_selector)},use:function(){var a=c.makeArray(arguments),b=a.shift();try{a.unshift(this),b.apply(this,a)}catch(d){"undefined"==typeof b?this.error("Plugin Error: called use() but plugin is not defined",d):c.isFunction(b)?this.error("Plugin Error",d):this.error("Plugin Error: called use() but '"+
b.toString()+"' is not a function",d)}return this},route:function(a,b,d){var j=this,e=[],g;!d&&c.isFunction(b)&&(d=b=a,a="any");a=a.toLowerCase();if(b.constructor==String){for(l.lastIndex=0;null!==(path_match=l.exec(b));)e.push(path_match[1]);b=RegExp("^"+b.replace(l,"([^/]+)")+"$")}"string"==typeof d&&(d=j[d]);g=function(a){var c={verb:a,path:b,callback:d,param_names:e};j.routes[a]=j.routes[a]||[];j.routes[a].push(c)};"any"===a?c.each(this.ROUTE_VERBS,function(a,b){g(b)}):g(a);return this},get:h("get"),
post:h("post"),put:h("put"),del:h("delete"),any:h("any"),mapRoutes:function(a){var b=this;c.each(a,function(a,c){b.route.apply(b,c)});return this},eventNamespace:function(){return["sammy-app",this.namespace].join("-")},bind:function(a,b,d){var c=this;"undefined"==typeof d&&(d=b);b=function(a,b){var e;b&&b.context?(e=b.context,delete b.context):e=new c.context_prototype(c,"bind",a.type,b);a.cleaned_type=a.type.replace(c.eventNamespace(),"");d.apply(e,[a,b])};this.listeners[a]||(this.listeners[a]=[]);
this.listeners[a].push(b);this.isRunning()&&this._listen(a,b);return this},trigger:function(a,b){this.$element().trigger([a,this.eventNamespace()].join("."),[b]);return this},refresh:function(){this.last_location=null;this.trigger("location-changed");return this},before:function(a,b){c.isFunction(a)&&(b=a,a={});this.befores.push([a,b]);return this},after:function(a){return this.bind("event-context-after",a)},around:function(a){this.arounds.push(a);return this},isRunning:function(){return this._running},
helpers:function(a){c.extend(this.context_prototype.prototype,a);return this},helper:function(a,b){this.context_prototype.prototype[a]=b;return this},run:function(a){if(this.isRunning())return!1;var b=this;c.each(this.listeners.toHash(),function(a,e){c.each(e,function(c,e){b._listen(a,e)})});this.trigger("run",{start_url:a});this._running=!0;this.last_location=null;""==this.getLocation()&&"undefined"!=typeof a&&this.setLocation(a);this._checkLocation();this.location_proxy.bind();this.bind("location-changed",
function(){b._checkLocation()});this.bind("submit",function(a){return!1===b._checkFormSubmission(c(a.target).closest("form"))?a.preventDefault():!1});c(window).bind("beforeunload",function(){b.unload()});return this.trigger("changed")},unload:function(){if(!this.isRunning())return!1;var a=this;this.trigger("unload");this.location_proxy.unbind();this.$element().unbind("submit").removeClass(a.eventNamespace());c.each(this.listeners.toHash(),function(b,d){c.each(d,function(d,c){a._unlisten(b,c)})});
this._running=!1;return this},bindToAllEvents:function(a){var b=this;c.each(this.APP_EVENTS,function(d,c){b.bind(c,a)});c.each(this.listeners.keys(!0),function(d,c){-1==b.APP_EVENTS.indexOf(c)&&b.bind(c,a)});return this},routablePath:function(a){return a.replace(p,"")},lookupRoute:function(a,b){var d=this,e=!1;this.trigger("lookup-route",{verb:a,path:b});"undefined"!=typeof this.routes[a]&&c.each(this.routes[a],function(a,c){if(d.routablePath(b).match(c.path))return e=c,!1});return e},runRoute:function(a,
b,d){var e=this,f=this.lookupRoute(a,b),g,k,i,n,o,r,h;this.log("runRoute",[a,b].join(" "));this.trigger("run-route",{verb:a,path:b,params:d});"undefined"==typeof d&&(d={});c.extend(d,this._parseQueryString(b));if(f){this.trigger("route-found",{route:f});if(null!==(path_params=f.path.exec(this.routablePath(b))))path_params.shift(),c.each(path_params,function(a,b){f.param_names[a]?d[f.param_names[a]]=m(b):(d.splat||(d.splat=[]),d.splat.push(m(b)))});g=new this.context_prototype(this,a,b,d);i=this.arounds.slice(0);
n=this.befores.slice(0);r=[g].concat(d.splat);k=function(){for(var a;0<n.length;)if(o=n.shift(),e.contextMatchesOptions(g,o[0])&&(a=o[1].apply(g,[g]),!1===a))return!1;e.last_route=f;g.trigger("event-context-before",{context:g});a=f.callback.apply(g,r);g.trigger("event-context-after",{context:g});return a};c.each(i.reverse(),function(a,b){var d=k;k=function(){return b.apply(g,[d])}});try{h=k()}catch(s){this.error(["500 Error",a,b].join(" "),s)}return h}return this.notFound(a,b)},contextMatchesOptions:function(a,
b,d){if("undefined"===typeof b||b=={})return!0;"undefined"===typeof d&&(d=!0);if("string"===typeof b||c.isFunction(b.test))b={path:b};if(b.only)return this.contextMatchesOptions(a,b.only,!0);if(b.except)return this.contextMatchesOptions(a,b.except,!1);var e=!0,f=!0;b.path&&(e=c.isFunction(b.path.test)?b.path.test(a.path):b.path.toString()===a.path);b.verb&&(f=b.verb===a.verb);return d?f&&e:!(f&&e)},getLocation:function(){return this.location_proxy.getLocation()},setLocation:function(a){return this.location_proxy.setLocation(a)},
swap:function(a){return this.$element().html(a)},notFound:function(a,b){var d=this.error(["404 Not Found",a,b].join(" "));return"get"===a?d:!0},error:function(a,b){b||(b=Error());b.message=[a,b.message].join(" ");this.trigger("error",{message:b.message,error:b});if(this.raise_errors)throw b;this.log(b.message,b)},_checkLocation:function(){var a,b;a=this.getLocation();a!=this.last_location&&(b=this.runRoute("get",a));this.last_location=a;return b},_checkFormSubmission:function(a){var b,d;this.trigger("check-form-submission",
{form:a});b=c(a);a=b.attr("action");d=c.trim(b.attr("method").toString().toLowerCase());if(!d||""==d)d="get";this.log("_checkFormSubmission",b,a,d);b=c.extend({},this._parseFormParams(b),{$form:b});a=this.runRoute(d,a,b);return"undefined"==typeof a?!1:a},_parseFormParams:function(a){var b={};c.each(a.serializeArray(),function(a,e){b[e.name]?c.isArray(b[e.name])?b[e.name].push(e.value):b[e.name]=[b[e.name],e.value]:b[e.name]=e.value});return b},_parseQueryString:function(a){var b={},d,c;if(a=a.match(p)){a=
a[1].split("&");for(c=0;c<a.length;c+=1)d=a[c].split("="),b[d[0]]=m(d[1])}return b},_listen:function(a,b){return this.$element().bind([a,this.eventNamespace()].join("."),b)},_unlisten:function(a,b){return this.$element().unbind([a,this.eventNamespace()].join("."),b)}});e.EventContext=function(a,b,c,j){this.app=a;this.verb=b;this.path=c;this.params=new e.Object(j)};e.EventContext.prototype=c.extend({},e.Object.prototype,{$element:function(){return this.app.$element()},partial:function(a,b,d){var e,
f,g,h="partial:"+a,i=this;if(f=a.match(/\.([^\.]+)$/))f=f[1];if((!f||!c.isFunction(i[f]))&&this.app.template_engine)f=this.app.template_engine;f&&(!c.isFunction(f)&&c.isFunction(i[f]))&&(f=i[f]);!d&&c.isFunction(b)&&(d=b,b={});g=c.isArray(b)?b:[b||{}];e=function(a){var b=a,e="";c.each(g,function(g,h){c.extend(h,i);c.isFunction(f)&&(b=f.apply(i,[a,h]));e=e+b;if(d)return d.apply(i,[b,g])});d||i.swap(e);i.trigger("changed")};this.app.cache_partials&&this.cache(h)?e.apply(i,[this.cache(h)]):c.get(a,function(a){i.app.cache_partials&&
i.cache(h,a);e.apply(i,[a])})},redirect:function(){var a;a=c.makeArray(arguments);var b=this.app.getLocation();1<a.length?(a.unshift("/"),a=this.join.apply(this,a)):a=a[0];this.trigger("redirect",{to:a});this.app.last_location=this.path;this.app.setLocation(a);b==a&&this.app.trigger("location-changed")},trigger:function(a,b){"undefined"==typeof b&&(b={});b.context||(b.context=this);return this.app.trigger(a,b)},eventNamespace:function(){return this.app.eventNamespace()},swap:function(a){return this.app.swap(a)},
notFound:function(){return this.app.notFound(this.verb,this.path)},toString:function(){return"Sammy.EventContext: "+[this.verb,this.path,this.params].join(" ")}});c.sammy=window.Sammy=e})(jQuery);
\ No newline at end of file
/*global TodoApp */
(function () {
'use strict';
var Todos = {
all: [],
visible: [],
flag: null,
createId: (function () {
// Creates a unique ID for every todoItem.
var s4 = function () {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
};
return function () {
return s4() + s4();
};
})(),
findOne: function (param, value) {
var todo = {};
Todos.all.forEach(function (thisTodo, i) {
if (thisTodo[param] === value) {
todo.todo = thisTodo;
todo.index = i;
}
});
return todo;
},
filter: function (param, value) {
return Todos.all.filter(function (thisTodo) {
return thisTodo[param] === value;
});
},
get: function (id) {
if (id && id !== 'active' && id !== 'completed') {
// We are looking for a particular todoItem.
return Todos.findOne('id', id);
} else if (id === 'active' || id === 'completed') {
// We either want to receive only the completed or active todoItems.
return Todos.filter('completed', id === 'completed');
} else {
// We want all of the todoItems.
return JSON.parse(localStorage.getItem('todos-sammyjs')) || [];
}
},
getData: function () {
return {
flag: Todos.flag,
all: Todos.all,
active: Todos.get('active'),
completed: Todos.get('completed'),
visible: Todos.get(Todos.flag)
};
},
save: function (e, data) {
Todos.all.push({
id: Todos.createId(),
name: data.name,
completed: data.completed
});
Todos.sync();
},
toggleCompleted: function (e, data) {
Todos.get(data.id).todo.completed = !Todos.get(data.id).todo.completed;
TodoApp.trigger('toggledTodoCompleted', {
id: data.id,
completed: Todos.get(data.id).todo.completed
});
Todos.sync();
},
toggleAllCompleted: function () {
var activeTodosLeft = Todos.get('active').length > 0;
Todos.all.forEach(function (thisTodo) {
thisTodo.completed = activeTodosLeft;
TodoApp.trigger('toggledTodoCompleted', {
id: thisTodo.id,
completed: thisTodo.completed
});
});
Todos.sync();
},
edit: function (e, data) {
if (!data.name) {
return Todos.remove(e, data);
}
Todos.get(data.id).todo.name = data.name;
Todos.syncQuiet();
},
removeCompleted: function () {
Todos.get('completed').forEach(function (thisTodo) {
Todos.remove(null, thisTodo);
});
},
remove: function (e, data) {
Todos.all.splice(Todos.get(data.id).index, 1);
Todos.sync();
},
fetchTodos: function (e, flag) {
// Called from each route's instantiation.
Todos.all = Todos.get();
Todos.flag = flag;
TodoApp.trigger('launch', Todos.getData());
Todos.sync();
},
syncQuiet: function () {
// Syncs data with `localStorage`, without forcing all of the todoItems
// to repaint.
localStorage.setItem('todos-sammyjs', JSON.stringify(Todos.all));
TodoApp.trigger('todosUpdatedQuiet', Todos.getData());
},
sync: function () {
// Syncs data with `localStorage`, and rebuilds the todoItems.
Todos.syncQuiet();
TodoApp.trigger('todosUpdated', Todos.getData());
}
};
TodoApp
.bind('fetchTodos', Todos.fetchTodos)
.bind('saveTodo', Todos.save)
.bind('doneEditingTodo', Todos.edit)
.bind('toggleTodoCompleted', Todos.toggleCompleted)
.bind('removeTodo', Todos.remove)
.bind('toggleAllTodosCompleted', Todos.toggleAllCompleted)
.bind('removeCompletedTodos', Todos.removeCompleted);
})();
/*global TodoApp */
(function () {
'use strict';
TodoApp.route('get', '#/active', function () {
TodoApp.trigger('fetchTodos', 'active');
});
})();
/*global TodoApp */
(function () {
'use strict';
TodoApp.route('get', '#/completed', function () {
TodoApp.trigger('fetchTodos', 'completed');
});
})();
/*global TodoApp */
(function () {
'use strict';
TodoApp.route('get', '#/', function () {
TodoApp.trigger('fetchTodos');
});
})();
/*global jQuery, TodoApp */
(function ($) {
'use strict';
var TodoItem = {
renderAllTodos: function (e, data) {
this.renderEach('templates/todoItem.template', data.visible).then(function () {
$('#todo-list').html(this.content);
TodoApp.trigger('todoItemsRendered', data);
});
},
toggleCompleteClass: function (e, data) {
if (data.completed) {
$('[data-id="' + data.id + '"]').addClass('completed');
} else {
$('[data-id="' + data.id + '"]').removeClass('completed');
}
},
editingTodo: function (e, data) {
var todo = $('[data-id="' + data.id + '"]');
todo.addClass('editing');
todo.find('.edit').focus().val(todo.find('.edit').val());
},
doneEditingTodo: function (e, data) {
var todo = $('[data-id="' + data.id + '"]');
todo.removeClass('editing');
if (data.name) {
todo.find('label').text(data.name);
todo.find('.edit').val(data.name);
}
}
};
TodoApp.bind('todosUpdated', TodoItem.renderAllTodos);
TodoApp.bind('toggleAllTodosCompleted', TodoItem.toggleCompleteClass);
TodoApp.bind('toggledTodoCompleted', TodoItem.toggleCompleteClass);
TodoApp.bind('editingTodo', TodoItem.editingTodo);
TodoApp.bind('cancelEditingTodo', TodoItem.doneEditingTodo);
TodoApp.bind('doneEditingTodo', TodoItem.doneEditingTodo);
})(jQuery);
/*global jQuery, TodoApp */
(function ($) {
'use strict';
var TodoList = {
elem: {
todoapp: '#todoapp',
main: '#main',
footer: '#footer'
},
render: function () {
TodoList.elem.todoapp = $(TodoList.elem.todoapp);
TodoList.elem.main = $(TodoList.elem.main);
TodoList.elem.footer = $(TodoList.elem.footer);
this.render('templates/todos.template').then(function () {
TodoList.elem.main.html(this.content);
TodoApp.trigger('todoListRendered');
});
},
refreshStats: function (e, data) {
var todoData = {
itemsLeft: data.active.length || 0,
completedCount: data.completed.length || 0,
flag: data.flag || ''
};
// Toggles the `#toggle-all` checkbox if all items are completed.
$('#toggle-all').prop('checked', data.completed.length === data.all.length ? 'checked' : false);
// Hides '#main' and '#footer' unless there are todoItems.
TodoList.elem.main.toggle(data.all.length > 0);
TodoList.elem.footer.toggle(data.all.length > 0);
this.render('templates/footer.template', todoData).then(function () {
TodoList.elem.footer.html(this.content);
});
}
};
TodoApp.bind('launch', TodoList.render);
TodoApp.bind('todoItemsRendered', TodoList.refreshStats);
})(jQuery);
# Sammy.js TodoMVC app # Sammy.js TodoMVC app
[Brandon Aaron](http://brandonaaron.net) wrote the original version of this application, which was then refactored and rewritten by Addy Osmani. [Brandon Aaron](http://brandonaaron.net) wrote the original version of this application, which was then refactored and rewritten by [Addy Osmani](https://github.com/addyosmani), followed by a complete rewrite and upgrade by [Stephen Sawchuk](https://github.com/stephenplusplus).
\ No newline at end of file
There was an error.
\ No newline at end of file
<span id="todo-count">
<strong><%= itemsLeft %></strong> <%= itemsLeft == 0 || itemsLeft > 1 ? 'items' : 'item' %> left
</span>
<ul id="filters">
<li>
<a <%= flag === '' ? 'class=selected' : '' %> href="#/">All</a>
</li>
<li>
<a <%= flag === 'active' ? 'class=selected' : '' %> href="#/active">Active</a>
</li>
<li>
<a <%= flag === 'completed' ? 'class=selected' : '' %> href="#/completed">Completed</a>
</li>
</ul>
<button id="clear-completed" <%= completedCount === 0 ? 'class=hidden' : '' %>>Clear completed (<%= completedCount %>)</button>
<li data-type="todo" data-id="<%= id %>" class="<%= done ? 'done' : '' %>">
<div class="todo">
<div class="display">
<input class="check" type="checkbox" <%= done ? 'checked' : '' %>/>
<span class="trashcan" data-type="todo" data-id="<%= id %>"></span>
<span contenteditable="true" data-type="todo" data-id="<%= id %>" class="todo-item"><%= name %></span>
</div>
</div>
</li>
<li data-id="<%= id %>" class="<%= completed ? 'completed' : '' %>">
<div class="view">
<input class="toggle" type="checkbox" <%= completed ? 'checked' : '' %>>
<label><%= name %></label>
<button class="destroy"></button>
</div>
<input class="edit" value="<%= name %>">
</li>
<h2 data-type="list" data-id="<%= list.id %>"></h2>
<% $.each(todos, function(index, todo) { %>
<li data-type="todo" data-id="<%= todo.id %>" class="<%= todo.done ? 'done' : '' %>">
<div class="todo">
<div class="display">
<input class="check" type="checkbox" <%= todo.done ? 'checked' : '' %>/>
<span class="trashcan" data-type="todo" data-id="<%= todo.id %>"></span><span contenteditable="true" data-type="todo" data-id="<%= todo.id %>" class="todo-item"><%= todo.name %></span>
</div>
</div>
</li>
<% }); %>
<input id="toggle-all" type="checkbox">
<label for="toggle-all">Mark all as complete</label>
<ul id="todo-list"></ul>
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment