Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

adding a few more technology stacks

  • Loading branch information...
commit ad400399bfbd0023c95b37121467041be39dcdc3 1 parent 848bfda
@addyosmani authored
Showing with 5,444 additions and 1 deletion.
  1. +23 −1 README.md
  2. +1 −0  option4_grails_mongo/README
  3. +7 −0 option4_grails_mongo/application.properties
  4. +5 −0 option4_grails_mongo/grails-app/conf/ApplicationResources.groovy
  5. +7 −0 option4_grails_mongo/grails-app/conf/BootStrap.groovy
  6. +46 −0 option4_grails_mongo/grails-app/conf/BuildConfig.groovy
  7. +94 −0 option4_grails_mongo/grails-app/conf/Config.groovy
  8. +14 −0 option4_grails_mongo/grails-app/conf/TodoResources.groovy
  9. +17 −0 option4_grails_mongo/grails-app/conf/UrlMappings.groovy
  10. +3 −0  option4_grails_mongo/grails-app/conf/spring/resources.groovy
  11. +27 −0 option4_grails_mongo/grails-app/controllers/todo/TodosController.groovy
  12. +12 −0 option4_grails_mongo/grails-app/domain/todo/Todo.groovy
  13. +11 −0 option4_grails_mongo/grails-app/views/error.gsp
  14. +82 −0 option4_grails_mongo/grails-app/views/index.gsp
  15. +12 −0 option4_grails_mongo/grails-app/views/layouts/main.gsp
  16. +1,231 −0 option4_grails_mongo/web-app/backbone.js
  17. BIN  option4_grails_mongo/web-app/destroy.png
  18. +311 −0 option4_grails_mongo/web-app/todos.css
  19. +237 −0 option4_grails_mongo/web-app/todos.js
  20. +999 −0 option4_grails_mongo/web-app/underscore.js
  21. +10 −0 option5_php_slim/.htaccess
  22. +2 −0  option5_php_slim/README.md
  23. BIN  option5_php_slim/destroy.png
  24. +77 −0 option5_php_slim/index.html
  25. +44 −0 option5_php_slim/index.php
  26. +530 −0 option5_php_slim/todos.css
  27. +253 −0 option5_php_slim/todos.js
  28. +6 −0 option5_php_slim/todos.sql
  29. +15 −0 option6_rails_coffeescript/Gemfile
  30. +119 −0 option6_rails_coffeescript/Gemfile.lock
  31. +27 −0 option6_rails_coffeescript/README.md
  32. +7 −0 option6_rails_coffeescript/Rakefile
  33. BIN  option6_rails_coffeescript/app/assets/images/destroy.png
  34. +108 −0 option6_rails_coffeescript/app/assets/javascripts/application.js.coffee
  35. +18 −0 option6_rails_coffeescript/app/assets/javascripts/collections/todos.js.coffee
  36. +18 −0 option6_rails_coffeescript/app/assets/javascripts/models/todo.js.coffee
  37. +10 −0 option6_rails_coffeescript/app/assets/javascripts/templates/todos/item.jst.ejs
  38. +14 −0 option6_rails_coffeescript/app/assets/javascripts/templates/todos/stats.jst.ejs
  39. +51 −0 option6_rails_coffeescript/app/assets/javascripts/views/todos/todo.js.coffee
  40. +4 −0 option6_rails_coffeescript/app/assets/stylesheets/application.css
  41. +530 −0 option6_rails_coffeescript/app/assets/stylesheets/todos.css
  42. +3 −0  option6_rails_coffeescript/app/controllers/application_controller.rb
  43. +3 −0  option6_rails_coffeescript/app/controllers/todos_controller.rb
  44. +3 −0  option6_rails_coffeescript/app/models/todo.rb
  45. +14 −0 option6_rails_coffeescript/app/views/layouts/application.html.erb
  46. +31 −0 option6_rails_coffeescript/app/views/todos/index.html.erb
  47. +4 −0 option6_rails_coffeescript/config.ru
  48. +65 −0 option6_rails_coffeescript/config/application.rb
  49. +6 −0 option6_rails_coffeescript/config/boot.rb
  50. +3 −0  option6_rails_coffeescript/config/database.yml
  51. +5 −0 option6_rails_coffeescript/config/environment.rb
  52. +37 −0 option6_rails_coffeescript/config/environments/development.rb
  53. +67 −0 option6_rails_coffeescript/config/environments/production.rb
  54. +37 −0 option6_rails_coffeescript/config/environments/test.rb
  55. +7 −0 option6_rails_coffeescript/config/initializers/backtrace_silencers.rb
  56. +15 −0 option6_rails_coffeescript/config/initializers/inflections.rb
  57. +5 −0 option6_rails_coffeescript/config/initializers/mime_types.rb
  58. +7 −0 option6_rails_coffeescript/config/initializers/secret_token.rb
  59. +8 −0 option6_rails_coffeescript/config/initializers/session_store.rb
  60. +14 −0 option6_rails_coffeescript/config/initializers/wrap_parameters.rb
  61. +5 −0 option6_rails_coffeescript/config/locales/en.yml
  62. +4 −0 option6_rails_coffeescript/config/routes.rb
  63. +9 −0 option6_rails_coffeescript/db/migrate/20120414043745_create_todos.rb
  64. +22 −0 option6_rails_coffeescript/db/schema.rb
  65. +26 −0 option6_rails_coffeescript/public/404.html
  66. +26 −0 option6_rails_coffeescript/public/422.html
  67. +25 −0 option6_rails_coffeescript/public/500.html
  68. 0  option6_rails_coffeescript/public/favicon.ico
  69. +5 −0 option6_rails_coffeescript/public/robots.txt
  70. +6 −0 option6_rails_coffeescript/script/rails
View
24 README.md
@@ -1,6 +1,6 @@
#Backbone Boilerplates
-Developers have been reqesting examples of how to integrate Backbone.js with a number of different technology stacks. Two common requests have included Node.js and Sinatra/Ruby but there have been a number of others too. To help with this, you can find three of these integration examples below. There are more to come soon.
+Developers have been reqesting examples of how to integrate Backbone.js with a number of different backend technology stacks. To help with this, you can find six of these integration examples in this repository, with their stacks listed below. There are more to come soon and I'm always happy to consider other stacks not already covered.
Option 1
=========
@@ -24,6 +24,28 @@ Option 3
* Sinatra
* MongoDB
+Option 4
+==========
+* Grails
+* MongoDB
+
+(thanks to [Lauri Piispanen](https://github.com/lauripiispanen))
+
+Option 5
+==========
+* PHP
+* Slim PHP RESTful framework
+* mySQL
+
+(thanks to [Joshua Stauter](https://github.com/dthtvwls))
+
+Option 6
+==========
+* Rails / Rails Asset Pipeline
+* CoffeeScript
+* Rails JSON API
+
+(also thanks to [Joshua Stauter](https://github.com/dthtvwls))
##Instructions
View
1  option4_grails_mongo/README
@@ -0,0 +1 @@
+Example to accompany blog post: http://lauripiispanen.github.com/blog/2012/01/31/building-a-backend-for-backbone-dot-js-todos-example-with-grails-and-mongodb/
View
7 option4_grails_mongo/application.properties
@@ -0,0 +1,7 @@
+#Grails Metadata file
+#Wed Jan 25 16:27:14 EET 2012
+app.grails.version=2.0.0
+app.name=todo
+app.servlet.version=2.5
+app.version=0.1
+plugins.mongodb=1.0.0.RC3
View
5 option4_grails_mongo/grails-app/conf/ApplicationResources.groovy
@@ -0,0 +1,5 @@
+modules = {
+ application {
+ resource url:'js/application.js'
+ }
+}
View
7 option4_grails_mongo/grails-app/conf/BootStrap.groovy
@@ -0,0 +1,7 @@
+class BootStrap {
+
+ def init = { servletContext ->
+ }
+ def destroy = {
+ }
+}
View
46 option4_grails_mongo/grails-app/conf/BuildConfig.groovy
@@ -0,0 +1,46 @@
+grails.servlet.version = "2.5" // Change depending on target container compliance (2.5 or 3.0)
+grails.project.class.dir = "target/classes"
+grails.project.test.class.dir = "target/test-classes"
+grails.project.test.reports.dir = "target/test-reports"
+grails.project.target.level = 1.6
+grails.project.source.level = 1.6
+//grails.project.war.file = "target/${appName}-${appVersion}.war"
+
+grails.project.dependency.resolution = {
+ // inherit Grails' default dependencies
+ inherits("global") {
+ // uncomment to disable ehcache
+ // excludes 'ehcache'
+ }
+ log "error" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
+ checksums true // Whether to verify checksums on resolve
+
+ repositories {
+ inherits true // Whether to inherit repository definitions from plugins
+ grailsPlugins()
+ grailsHome()
+ grailsCentral()
+ mavenCentral()
+
+ // uncomment these to enable remote dependency resolution from public Maven repositories
+ //mavenCentral()
+ //mavenLocal()
+ //mavenRepo "http://snapshots.repository.codehaus.org"
+ //mavenRepo "http://repository.codehaus.org"
+ //mavenRepo "http://download.java.net/maven/2/"
+ //mavenRepo "http://repository.jboss.com/maven2/"
+ }
+ dependencies {
+ // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.
+
+ // runtime 'mysql:mysql-connector-java:5.1.16'
+ }
+
+ plugins {
+ runtime ":mongodb:latest.integration"
+ runtime ":jquery:1.7.1"
+ runtime ":resources:1.1.5"
+
+ build ":tomcat:$grailsVersion"
+ }
+}
View
94 option4_grails_mongo/grails-app/conf/Config.groovy
@@ -0,0 +1,94 @@
+// locations to search for config files that get merged into the main config
+// config files can either be Java properties files or ConfigSlurper scripts
+
+// grails.config.locations = [ "classpath:${appName}-config.properties",
+// "classpath:${appName}-config.groovy",
+// "file:${userHome}/.grails/${appName}-config.properties",
+// "file:${userHome}/.grails/${appName}-config.groovy"]
+
+// if (System.properties["${appName}.config.location"]) {
+// grails.config.locations << "file:" + System.properties["${appName}.config.location"]
+// }
+
+
+grails.project.groupId = appName // change this to alter the default package name and Maven publishing destination
+grails.mime.file.extensions = true // enables the parsing of file extensions from URLs into the request format
+grails.mime.use.accept.header = false
+grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
+ xml: ['text/xml', 'application/xml'],
+ text: 'text/plain',
+ js: 'text/javascript',
+ rss: 'application/rss+xml',
+ atom: 'application/atom+xml',
+ css: 'text/css',
+ csv: 'text/csv',
+ all: '*/*',
+ json: ['application/json','text/json'],
+ form: 'application/x-www-form-urlencoded',
+ multipartForm: 'multipart/form-data'
+ ]
+
+// URL Mapping Cache Max Size, defaults to 5000
+//grails.urlmapping.cache.maxsize = 1000
+
+// What URL patterns should be processed by the resources plugin
+grails.resources.adhoc.patterns = ['/images/*', '/css/*', '/js/*', '/plugins/*']
+
+grails.app.context="/"
+
+// The default codec used to encode data with ${}
+grails.views.default.codec = "none" // none, html, base64
+grails.views.gsp.encoding = "UTF-8"
+grails.converters.encoding = "UTF-8"
+// enable Sitemesh preprocessing of GSP pages
+grails.views.gsp.sitemesh.preprocess = true
+// scaffolding templates configuration
+grails.scaffolding.templates.domainSuffix = 'Instance'
+
+// Set to false to use the new Grails 1.2 JSONBuilder in the render method
+grails.json.legacy.builder = false
+// enabled native2ascii conversion of i18n properties files
+grails.enable.native2ascii = true
+// packages to include in Spring bean scanning
+grails.spring.bean.packages = []
+// whether to disable processing of multi part requests
+grails.web.disable.multipart=false
+
+// request parameters to mask when logging exceptions
+grails.exceptionresolver.params.exclude = ['password']
+
+// enable query caching by default
+grails.hibernate.cache.queries = true
+
+// set per-environment serverURL stem for creating absolute links
+environments {
+ development {
+ grails.logging.jul.usebridge = true
+ }
+ production {
+ grails.logging.jul.usebridge = false
+ // TODO: grails.serverURL = "http://www.changeme.com"
+ }
+}
+
+// log4j configuration
+log4j = {
+ // Example of changing the log pattern for the default console
+ // appender:
+ //
+ //appenders {
+ // console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
+ //}
+
+ error 'org.codehaus.groovy.grails.web.servlet', // controllers
+ 'org.codehaus.groovy.grails.web.pages', // GSP
+ 'org.codehaus.groovy.grails.web.sitemesh', // layouts
+ 'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
+ 'org.codehaus.groovy.grails.web.mapping', // URL mapping
+ 'org.codehaus.groovy.grails.commons', // core / classloading
+ 'org.codehaus.groovy.grails.plugins', // plugins
+ 'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
+ 'org.springframework',
+ 'org.hibernate',
+ 'net.sf.ehcache.hibernate'
+}
View
14 option4_grails_mongo/grails-app/conf/TodoResources.groovy
@@ -0,0 +1,14 @@
+modules = {
+ todo {
+ dependsOn 'jquery, underscore, backbone'
+
+ resource url: '/todos.css'
+ resource url: '/todos.js'
+ }
+ backbone {
+ resource url: '/backbone.js'
+ }
+ underscore {
+ resource url: '/underscore.js'
+ }
+}
View
17 option4_grails_mongo/grails-app/conf/UrlMappings.groovy
@@ -0,0 +1,17 @@
+class UrlMappings {
+
+ static mappings = {
+ "/$controller/$action?/$id?"{
+ constraints {
+ // apply constraints here
+ }
+ }
+
+ "/todos/$id?"(controller: "todos") {
+ action = [GET:"list", POST: "save", DELETE: "delete", PUT: "edit"]
+ }
+
+ "/"(view:"/index")
+ "500"(view:'/error')
+ }
+}
View
3  option4_grails_mongo/grails-app/conf/spring/resources.groovy
@@ -0,0 +1,3 @@
+// Place your Spring DSL code here
+beans = {
+}
View
27 option4_grails_mongo/grails-app/controllers/todo/TodosController.groovy
@@ -0,0 +1,27 @@
+package todo
+
+import grails.converters.JSON
+
+class TodosController {
+
+ def index() {
+ render( Todo.findAll() as JSON )
+ }
+
+ def save() {
+ def todo = new Todo(request.JSON);
+ render( todo.save() as JSON )
+ }
+
+ def delete() {
+ def todo = Todo.findById(params.id)
+ todo?.delete()
+ render(todo as JSON );
+ }
+
+ def edit() {
+ def todo = Todo.findById(params.id)
+ bindData(todo, request.JSON)
+ render(todo.save() as JSON )
+ }
+}
View
12 option4_grails_mongo/grails-app/domain/todo/Todo.groovy
@@ -0,0 +1,12 @@
+package todo
+
+class Todo {
+
+ boolean done
+ int order
+ String text
+
+ static constraints = {
+ text(nullable: false, empty: false)
+ }
+}
View
11 option4_grails_mongo/grails-app/views/error.gsp
@@ -0,0 +1,11 @@
+<!doctype html>
+<html>
+ <head>
+ <title>Grails Runtime Exception</title>
+ <meta name="layout" content="main">
+ <link rel="stylesheet" href="${resource(dir: 'css', file: 'errors.css')}" type="text/css">
+ </head>
+ <body>
+ <g:renderException exception="${exception}" />
+ </body>
+</html>
View
82 option4_grails_mongo/grails-app/views/index.gsp
@@ -0,0 +1,82 @@
+<!DOCTYPE html>
+<html>
+
+ <head>
+ <title>Backbone Demo: Todos</title>
+ <r:require module="todo" />
+ <meta name="layout" content="main">
+ </head>
+
+ <body>
+
+ <!-- Todo App Interface -->
+
+ <div id="todoapp">
+
+ <div class="title">
+ <h1>Todos</h1>
+ </div>
+
+ <div class="content">
+
+ <div id="create-todo">
+ <input id="new-todo" placeholder="What needs to be done?" type="text" />
+ <span class="ui-tooltip-top" style="display:none;">Press Enter to save this task</span>
+ </div>
+
+ <div id="todos">
+ <ul id="todo-list"></ul>
+ </div>
+
+ <div id="todo-stats"></div>
+
+ </div>
+
+ </div>
+
+ <ul id="instructions">
+ <li>Double-click to edit a todo.</li>
+ <li><a href="../../docs/todos.html">View the annotated source.</a></li>
+ </ul>
+
+ <div id="credits">
+ Created by
+ <br />
+ <a href="http://jgn.me/">J&eacute;r&ocirc;me Gravel-Niquet</a>
+ </div>
+
+ <!-- Templates -->
+
+ <script type="text/template" id="item-template">
+ <div class="todo {{ done ? 'done' : '' }}">
+ <div class="display">
+ <input class="check" type="checkbox" {{ done ? 'checked="checked"' : '' }} />
+ <div class="todo-text"></div>
+ <span class="todo-destroy"></span>
+ </div>
+ <div class="edit">
+ <input class="todo-input" type="text" value="" />
+ </div>
+ </div>
+ </script>
+
+ <script type="text/template" id="stats-template">
+ {! if (total) { !}
+ <span class="todo-count">
+ <span class="number">{{ remaining }}</span>
+ <span class="word">{{ remaining == 1 ? 'item' : 'items' }}</span> left.
+ </span>
+ {! } !}
+ {! if (done) { !}
+ <span class="todo-clear">
+ <a href="#">
+ Clear <span class="number-done">{{ done }}</span>
+ completed <span class="word-done">{{ done == 1 ? 'item' : 'items' }}</span>
+ </a>
+ </span>
+ {! } !}
+ </script>
+
+ </body>
+
+</html>
View
12 option4_grails_mongo/grails-app/views/layouts/main.gsp
@@ -0,0 +1,12 @@
+<!doctype html>
+<html>
+ <head>
+ <title><g:layoutTitle default="Grails"/></title>
+ <g:layoutHead/>
+ <r:layoutResources />
+ </head>
+ <body>
+ <g:layoutBody/>
+ <r:layoutResources />
+ </body>
+</html>
View
1,231 option4_grails_mongo/web-app/backbone.js
@@ -0,0 +1,1231 @@
+// Backbone.js 0.5.3
+// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
+// Backbone may be freely distributed under the MIT license.
+// For all details and documentation:
+// http://backbonejs.org
+
+(function(){
+
+ // Initial Setup
+ // -------------
+
+ // Save a reference to the global object.
+ var root = this;
+
+ // Save the previous value of the `Backbone` variable.
+ var previousBackbone = root.Backbone;
+
+ // Create a local reference to slice/splice.
+ var slice = Array.prototype.slice;
+ var splice = Array.prototype.splice;
+
+ // The top-level namespace. All public Backbone classes and modules will
+ // be attached to this. Exported for both CommonJS and the browser.
+ var Backbone;
+ if (typeof exports !== 'undefined') {
+ Backbone = exports;
+ } else {
+ Backbone = root.Backbone = {};
+ }
+
+ // Current version of the library. Keep in sync with `package.json`.
+ Backbone.VERSION = '0.5.3';
+
+ // Require Underscore, if we're on the server, and it's not already present.
+ var _ = root._;
+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
+
+ // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
+ var $ = root.jQuery || root.Zepto || root.ender;
+
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
+ // to its previous owner. Returns a reference to this Backbone object.
+ Backbone.noConflict = function() {
+ root.Backbone = previousBackbone;
+ return this;
+ };
+
+ // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
+ // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
+ // set a `X-Http-Method-Override` header.
+ Backbone.emulateHTTP = false;
+
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
+ // `application/json` requests ... will encode the body as
+ // `application/x-www-form-urlencoded` instead and will send the model in a
+ // form param named `model`.
+ Backbone.emulateJSON = false;
+
+ // Backbone.Events
+ // -----------------
+
+ // A module that can be mixed in to *any object* in order to provide it with
+ // custom events. You may bind with `on` or remove with `off` callback functions
+ // to an event; trigger`-ing an event fires all callbacks in succession.
+ //
+ // var object = {};
+ // _.extend(object, Backbone.Events);
+ // object.on('expand', function(){ alert('expanded'); });
+ // object.trigger('expand');
+ //
+ Backbone.Events = {
+
+ // Bind an event, specified by a string name, `ev`, to a `callback`
+ // function. Passing `"all"` will bind the callback to all events fired.
+ on: function(events, callback, context) {
+ var ev;
+ events = events.split(/\s+/);
+ var calls = this._callbacks || (this._callbacks = {});
+ while (ev = events.shift()) {
+ // Create an immutable callback list, allowing traversal during
+ // modification. The tail is an empty object that will always be used
+ // as the next node.
+ var list = calls[ev] || (calls[ev] = {});
+ var tail = list.tail || (list.tail = list.next = {});
+ tail.callback = callback;
+ tail.context = context;
+ list.tail = tail.next = {};
+ }
+ return this;
+ },
+
+ // Remove one or many callbacks. If `context` is null, removes all callbacks
+ // with that function. If `callback` is null, removes all callbacks for the
+ // event. If `ev` is null, removes all bound callbacks for all events.
+ off: function(events, callback, context) {
+ var ev, calls, node;
+ if (!events) {
+ delete this._callbacks;
+ } else if (calls = this._callbacks) {
+ events = events.split(/\s+/);
+ while (ev = events.shift()) {
+ node = calls[ev];
+ delete calls[ev];
+ if (!callback || !node) continue;
+ // Create a new list, omitting the indicated event/context pairs.
+ while ((node = node.next) && node.next) {
+ if (node.callback === callback &&
+ (!context || node.context === context)) continue;
+ this.on(ev, node.callback, node.context);
+ }
+ }
+ }
+ return this;
+ },
+
+ // Trigger an event, firing all bound callbacks. Callbacks are passed the
+ // same arguments as `trigger` is, apart from the event name.
+ // Listening for `"all"` passes the true event name as the first argument.
+ trigger: function(events) {
+ var event, node, calls, tail, args, all, rest;
+ if (!(calls = this._callbacks)) return this;
+ all = calls['all'];
+ (events = events.split(/\s+/)).push(null);
+ // Save references to the current heads & tails.
+ while (event = events.shift()) {
+ if (all) events.push({next: all.next, tail: all.tail, event: event});
+ if (!(node = calls[event])) continue;
+ events.push({next: node.next, tail: node.tail});
+ }
+ // Traverse each list, stopping when the saved tail is reached.
+ rest = slice.call(arguments, 1);
+ while (node = events.pop()) {
+ tail = node.tail;
+ args = node.event ? [node.event].concat(rest) : rest;
+ while ((node = node.next) !== tail) {
+ node.callback.apply(node.context || this, args);
+ }
+ }
+ return this;
+ }
+
+ };
+
+ // Aliases for backwards compatibility.
+ Backbone.Events.bind = Backbone.Events.on;
+ Backbone.Events.unbind = Backbone.Events.off;
+
+ // Backbone.Model
+ // --------------
+
+ // Create a new model, with defined attributes. A client id (`cid`)
+ // is automatically generated and assigned for you.
+ Backbone.Model = function(attributes, options) {
+ var defaults;
+ attributes || (attributes = {});
+ if (options && options.parse) attributes = this.parse(attributes);
+ if (defaults = getValue(this, 'defaults')) {
+ attributes = _.extend({}, defaults, attributes);
+ }
+ if (options && options.collection) this.collection = options.collection;
+ this.attributes = {};
+ this._escapedAttributes = {};
+ this.cid = _.uniqueId('c');
+ if (!this.set(attributes, {silent: true})) {
+ throw new Error("Can't create an invalid model");
+ }
+ this._changed = false;
+ this._previousAttributes = _.clone(this.attributes);
+ this.initialize.apply(this, arguments);
+ };
+
+ // Attach all inheritable methods to the Model prototype.
+ _.extend(Backbone.Model.prototype, Backbone.Events, {
+
+ // Has the item been changed since the last `"change"` event?
+ _changed: false,
+
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
+ // CouchDB users may want to set this to `"_id"`.
+ idAttribute: 'id',
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // Return a copy of the model's `attributes` object.
+ toJSON: function() {
+ return _.clone(this.attributes);
+ },
+
+ // Get the value of an attribute.
+ get: function(attr) {
+ return this.attributes[attr];
+ },
+
+ // Get the HTML-escaped value of an attribute.
+ escape: function(attr) {
+ var html;
+ if (html = this._escapedAttributes[attr]) return html;
+ var val = this.attributes[attr];
+ return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val);
+ },
+
+ // Returns `true` if the attribute contains a value that is not null
+ // or undefined.
+ has: function(attr) {
+ return this.attributes[attr] != null;
+ },
+
+ // Set a hash of model attributes on the object, firing `"change"` unless
+ // you choose to silence it.
+ set: function(key, value, options) {
+ var attrs, attr, val;
+ if (_.isObject(key) || key == null) {
+ attrs = key;
+ options = value;
+ } else {
+ attrs = {};
+ attrs[key] = value;
+ }
+
+ // Extract attributes and options.
+ options || (options = {});
+ if (!attrs) return this;
+ if (attrs instanceof Backbone.Model) attrs = attrs.attributes;
+ if (options.unset) for (var attr in attrs) attrs[attr] = void 0;
+ var now = this.attributes, escaped = this._escapedAttributes;
+
+ // Run validation.
+ if (this.validate && !this._performValidation(attrs, options)) return false;
+
+ // Check for changes of `id`.
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
+
+ // We're about to start triggering change events.
+ var alreadyChanging = this._changing;
+ this._changing = true;
+
+ // Update attributes.
+ var changes = {};
+ for (attr in attrs) {
+ val = attrs[attr];
+ if (!_.isEqual(now[attr], val) || (options.unset && (attr in now))) {
+ delete escaped[attr];
+ this._changed = true;
+ changes[attr] = val;
+ }
+ options.unset ? delete now[attr] : now[attr] = val;
+ }
+
+ // Fire `change:attribute` events.
+ for (var attr in changes) {
+ if (!options.silent) this.trigger('change:' + attr, this, changes[attr], options);
+ }
+
+ // Fire the `"change"` event, if the model has been changed.
+ if (!alreadyChanging) {
+ if (!options.silent && this._changed) this.change(options);
+ this._changing = false;
+ }
+ return this;
+ },
+
+ // Remove an attribute from the model, firing `"change"` unless you choose
+ // to silence it. `unset` is a noop if the attribute doesn't exist.
+ unset: function(attr, options) {
+ (options || (options = {})).unset = true;
+ return this.set(attr, null, options);
+ },
+
+ // Clear all attributes on the model, firing `"change"` unless you choose
+ // to silence it.
+ clear: function(options) {
+ (options || (options = {})).unset = true;
+ return this.set(_.clone(this.attributes), options);
+ },
+
+ // Fetch the model from the server. If the server's representation of the
+ // model differs from its current attributes, they will be overriden,
+ // triggering a `"change"` event.
+ fetch: function(options) {
+ options = options ? _.clone(options) : {};
+ var model = this;
+ var success = options.success;
+ options.success = function(resp, status, xhr) {
+ if (!model.set(model.parse(resp, xhr), options)) return false;
+ if (success) success(model, resp);
+ };
+ options.error = Backbone.wrapError(options.error, model, options);
+ return (this.sync || Backbone.sync).call(this, 'read', this, options);
+ },
+
+ // Set a hash of model attributes, and sync the model to the server.
+ // If the server returns an attributes hash that differs, the model's
+ // state will be `set` again.
+ save: function(key, value, options) {
+ var attrs;
+ if (_.isObject(key) || key == null) {
+ attrs = key;
+ options = value;
+ } else {
+ attrs = {};
+ attrs[key] = value;
+ }
+
+ options = options ? _.clone(options) : {};
+ if (attrs && !this[options.wait ? '_performValidation' : 'set'](attrs, options)) return false;
+ var model = this;
+ var success = options.success;
+ options.success = function(resp, status, xhr) {
+ var serverAttrs = model.parse(resp, xhr);
+ if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
+ if (!model.set(serverAttrs, options)) return false;
+ if (success) {
+ success(model, resp);
+ } else {
+ model.trigger('sync', model, resp, options);
+ }
+ };
+ options.error = Backbone.wrapError(options.error, model, options);
+ var method = this.isNew() ? 'create' : 'update';
+ return (this.sync || Backbone.sync).call(this, method, this, options);
+ },
+
+ // Destroy this model on the server if it was already persisted.
+ // Optimistically removes the model from its collection, if it has one.
+ // If `wait: true` is passed, waits for the server to respond before removal.
+ destroy: function(options) {
+ options = options ? _.clone(options) : {};
+ var model = this;
+ var success = options.success;
+
+ var triggerDestroy = function() {
+ model.trigger('destroy', model, model.collection, options);
+ };
+
+ if (this.isNew()) return triggerDestroy();
+ options.success = function(resp) {
+ if (options.wait) triggerDestroy();
+ if (success) {
+ success(model, resp);
+ } else {
+ model.trigger('sync', model, resp, options);
+ }
+ };
+ options.error = Backbone.wrapError(options.error, model, options);
+ var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options);
+ if (!options.wait) triggerDestroy();
+ return xhr;
+ },
+
+ // Default URL for the model's representation on the server -- if you're
+ // using Backbone's restful methods, override this to change the endpoint
+ // that will be called.
+ url: function() {
+ var base = getValue(this.collection, 'url') || getValue(this, 'urlRoot') || urlError();
+ if (this.isNew()) return base;
+ return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
+ },
+
+ // **parse** converts a response into the hash of attributes to be `set` on
+ // the model. The default implementation is just to pass the response along.
+ parse: function(resp, xhr) {
+ return resp;
+ },
+
+ // Create a new model with identical attributes to this one.
+ clone: function() {
+ return new this.constructor(this.attributes);
+ },
+
+ // A model is new if it has never been saved to the server, and lacks an id.
+ isNew: function() {
+ return this.id == null;
+ },
+
+ // Call this method to manually fire a `change` event for this model.
+ // Calling this will cause all objects observing the model to update.
+ change: function(options) {
+ this.trigger('change', this, options);
+ this._previousAttributes = _.clone(this.attributes);
+ this._changed = false;
+ },
+
+ // Determine if the model has changed since the last `"change"` event.
+ // If you specify an attribute name, determine if that attribute has changed.
+ hasChanged: function(attr) {
+ if (attr) return !_.isEqual(this._previousAttributes[attr], this.attributes[attr]);
+ return this._changed;
+ },
+
+ // Return an object containing all the attributes that have changed, or
+ // false if there are no changed attributes. Useful for determining what
+ // parts of a view need to be updated and/or what attributes need to be
+ // persisted to the server. Unset attributes will be set to undefined.
+ changedAttributes: function(now) {
+ if (!this._changed) return false;
+ now || (now = this.attributes);
+ var changed = false, old = this._previousAttributes;
+ for (var attr in now) {
+ if (_.isEqual(old[attr], now[attr])) continue;
+ (changed || (changed = {}))[attr] = now[attr];
+ }
+ for (var attr in old) {
+ if (!(attr in now)) (changed || (changed = {}))[attr] = void 0;
+ }
+ return changed;
+ },
+
+ // Get the previous value of an attribute, recorded at the time the last
+ // `"change"` event was fired.
+ previous: function(attr) {
+ if (!attr || !this._previousAttributes) return null;
+ return this._previousAttributes[attr];
+ },
+
+ // Get all of the attributes of the model at the time of the previous
+ // `"change"` event.
+ previousAttributes: function() {
+ return _.clone(this._previousAttributes);
+ },
+
+ // Run validation against a set of incoming attributes, returning `true`
+ // if all is well. If a specific `error` callback has been passed,
+ // call that instead of firing the general `"error"` event.
+ _performValidation: function(attrs, options) {
+ var newAttrs = _.extend({}, this.attributes, attrs);
+ var error = this.validate(newAttrs, options);
+ if (error) {
+ if (options.error) {
+ options.error(this, error, options);
+ } else {
+ this.trigger('error', this, error, options);
+ }
+ return false;
+ }
+ return true;
+ }
+
+ });
+
+ // Backbone.Collection
+ // -------------------
+
+ // Provides a standard collection class for our sets of models, ordered
+ // or unordered. If a `comparator` is specified, the Collection will maintain
+ // its models in sort order, as they're added and removed.
+ Backbone.Collection = function(models, options) {
+ options || (options = {});
+ if (options.comparator) this.comparator = options.comparator;
+ this._reset();
+ this.initialize.apply(this, arguments);
+ if (models) this.reset(models, {silent: true, parse: options.parse});
+ };
+
+ // Define the Collection's inheritable methods.
+ _.extend(Backbone.Collection.prototype, Backbone.Events, {
+
+ // The default model for a collection is just a **Backbone.Model**.
+ // This should be overridden in most cases.
+ model: Backbone.Model,
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // The JSON representation of a Collection is an array of the
+ // models' attributes.
+ toJSON: function() {
+ return this.map(function(model){ return model.toJSON(); });
+ },
+
+ // Add a model, or list of models to the set. Pass **silent** to avoid
+ // firing the `add` event for every new model.
+ add: function(models, options) {
+ var i, index, length, model, cids = {};
+ options || (options = {});
+ models = _.isArray(models) ? models.slice() : [models];
+ for (i = 0, length = models.length; i < length; i++) {
+ if (!(model = models[i] = this._prepareModel(models[i], options))) {
+ throw new Error("Can't add an invalid model to a collection");
+ }
+ var hasId = model.id != null;
+ if (this._byCid[model.cid] || (hasId && this._byId[model.id])) {
+ throw new Error("Can't add the same model to a collection twice");
+ }
+ }
+ for (i = 0; i < length; i++) {
+ (model = models[i]).on('all', this._onModelEvent, this);
+ this._byCid[model.cid] = model;
+ if (model.id != null) this._byId[model.id] = model;
+ cids[model.cid] = true;
+ }
+ this.length += length;
+ index = options.at != null ? options.at : this.models.length;
+ splice.apply(this.models, [index, 0].concat(models));
+ if (this.comparator) this.sort({silent: true});
+ if (options.silent) return this;
+ for (i = 0, length = this.models.length; i < length; i++) {
+ if (!cids[(model = this.models[i]).cid]) continue;
+ options.index = i;
+ model.trigger('add', model, this, options);
+ }
+ return this;
+ },
+
+ // Remove a model, or a list of models from the set. Pass silent to avoid
+ // firing the `remove` event for every model removed.
+ remove: function(models, options) {
+ var i, index, model;
+ options || (options = {});
+ models = _.isArray(models) ? models.slice() : [models];
+ for (i = 0, l = models.length; i < l; i++) {
+ model = this.getByCid(models[i]) || this.get(models[i]);
+ if (!model) continue;
+ delete this._byId[model.id];
+ delete this._byCid[model.cid];
+ index = this.indexOf(model);
+ this.models.splice(index, 1);
+ this.length--;
+ if (!options.silent) {
+ options.index = index;
+ model.trigger('remove', model, this, options);
+ }
+ this._removeReference(model);
+ }
+ return this;
+ },
+
+ // Get a model from the set by id.
+ get: function(id) {
+ if (id == null) return null;
+ return this._byId[id.id != null ? id.id : id];
+ },
+
+ // Get a model from the set by client id.
+ getByCid: function(cid) {
+ return cid && this._byCid[cid.cid || cid];
+ },
+
+ // Get the model at the given index.
+ at: function(index) {
+ return this.models[index];
+ },
+
+ // Force the collection to re-sort itself. You don't need to call this under
+ // normal circumstances, as the set will maintain sort order as each item
+ // is added.
+ sort: function(options) {
+ options || (options = {});
+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
+ var boundComparator = _.bind(this.comparator, this);
+ if (this.comparator.length == 1) {
+ this.models = this.sortBy(boundComparator);
+ } else {
+ this.models.sort(boundComparator);
+ }
+ if (!options.silent) this.trigger('reset', this, options);
+ return this;
+ },
+
+ // Pluck an attribute from each model in the collection.
+ pluck: function(attr) {
+ return _.map(this.models, function(model){ return model.get(attr); });
+ },
+
+ // When you have more items than you want to add or remove individually,
+ // you can reset the entire set with a new list of models, without firing
+ // any `add` or `remove` events. Fires `reset` when finished.
+ reset: function(models, options) {
+ models || (models = []);
+ options || (options = {});
+ for (var i = 0, l = this.models.length; i < l; i++) {
+ this._removeReference(this.models[i]);
+ }
+ this._reset();
+ this.add(models, {silent: true, parse: options.parse});
+ if (!options.silent) this.trigger('reset', this, options);
+ return this;
+ },
+
+ // Fetch the default set of models for this collection, resetting the
+ // collection when they arrive. If `add: true` is passed, appends the
+ // models to the collection instead of resetting.
+ fetch: function(options) {
+ options = options ? _.clone(options) : {};
+ if (options.parse === undefined) options.parse = true;
+ var collection = this;
+ var success = options.success;
+ options.success = function(resp, status, xhr) {
+ collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
+ if (success) success(collection, resp);
+ };
+ options.error = Backbone.wrapError(options.error, collection, options);
+ return (this.sync || Backbone.sync).call(this, 'read', this, options);
+ },
+
+ // Create a new instance of a model in this collection. Add the model to the
+ // collection immediately, unless `wait: true` is passed, in which case we
+ // wait for the server to agree.
+ create: function(model, options) {
+ var coll = this;
+ options = options ? _.clone(options) : {};
+ model = this._prepareModel(model, options);
+ if (!model) return false;
+ if (!options.wait) coll.add(model, options);
+ var success = options.success;
+ options.success = function(nextModel, resp, xhr) {
+ if (options.wait) coll.add(nextModel, options);
+ if (success) {
+ success(nextModel, resp);
+ } else {
+ nextModel.trigger('sync', model, resp, options);
+ }
+ };
+ model.save(null, options);
+ return model;
+ },
+
+ // **parse** converts a response into a list of models to be added to the
+ // collection. The default implementation is just to pass it through.
+ parse: function(resp, xhr) {
+ return resp;
+ },
+
+ // Proxy to _'s chain. Can't be proxied the same way the rest of the
+ // underscore methods are proxied because it relies on the underscore
+ // constructor.
+ chain: function () {
+ return _(this.models).chain();
+ },
+
+ // Reset all internal state. Called when the collection is reset.
+ _reset: function(options) {
+ this.length = 0;
+ this.models = [];
+ this._byId = {};
+ this._byCid = {};
+ },
+
+ // Prepare a model to be added to this collection
+ _prepareModel: function(model, options) {
+ if (!(model instanceof Backbone.Model)) {
+ var attrs = model;
+ options.collection = this;
+ model = new this.model(attrs, options);
+ if (model.validate && !model._performValidation(model.attributes, options)) model = false;
+ } else if (!model.collection) {
+ model.collection = this;
+ }
+ return model;
+ },
+
+ // Internal method to remove a model's ties to a collection.
+ _removeReference: function(model) {
+ if (this == model.collection) {
+ delete model.collection;
+ }
+ model.off('all', this._onModelEvent, this);
+ },
+
+ // Internal method called every time a model in the set fires an event.
+ // Sets need to update their indexes when models change ids. All other
+ // events simply proxy through. "add" and "remove" events that originate
+ // in other collections are ignored.
+ _onModelEvent: function(ev, model, collection, options) {
+ if ((ev == 'add' || ev == 'remove') && collection != this) return;
+ if (ev == 'destroy') {
+ this.remove(model, options);
+ }
+ if (model && ev === 'change:' + model.idAttribute) {
+ delete this._byId[model.previous(model.idAttribute)];
+ this._byId[model.id] = model;
+ }
+ this.trigger.apply(this, arguments);
+ }
+
+ });
+
+ // Underscore methods that we want to implement on the Collection.
+ var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find',
+ 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any',
+ 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex',
+ 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf',
+ 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];
+
+ // Mix in each Underscore method as a proxy to `Collection#models`.
+ _.each(methods, function(method) {
+ Backbone.Collection.prototype[method] = function() {
+ return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
+ };
+ });
+
+ // Backbone.Router
+ // -------------------
+
+ // Routers map faux-URLs to actions, and fire events when routes are
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
+ Backbone.Router = function(options) {
+ options || (options = {});
+ if (options.routes) this.routes = options.routes;
+ this._bindRoutes();
+ this.initialize.apply(this, arguments);
+ };
+
+ // Cached regular expressions for matching named param parts and splatted
+ // parts of route strings.
+ var namedParam = /:\w+/g;
+ var splatParam = /\*\w+/g;
+ var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
+
+ // Set up all inheritable **Backbone.Router** properties and methods.
+ _.extend(Backbone.Router.prototype, Backbone.Events, {
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // Manually bind a single named route to a callback. For example:
+ //
+ // this.route('search/:query/p:num', 'search', function(query, num) {
+ // ...
+ // });
+ //
+ route: function(route, name, callback) {
+ Backbone.history || (Backbone.history = new Backbone.History);
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
+ if (!callback) callback = this[name];
+ Backbone.history.route(route, _.bind(function(fragment) {
+ var args = this._extractParameters(route, fragment);
+ callback && callback.apply(this, args);
+ this.trigger.apply(this, ['route:' + name].concat(args));
+ Backbone.history.trigger('route', this, name, args);
+ }, this));
+ },
+
+ // Simple proxy to `Backbone.history` to save a fragment into the history.
+ navigate: function(fragment, options) {
+ Backbone.history.navigate(fragment, options);
+ },
+
+ // Bind all defined routes to `Backbone.history`. We have to reverse the
+ // order of the routes here to support behavior where the most general
+ // routes can be defined at the bottom of the route map.
+ _bindRoutes: function() {
+ if (!this.routes) return;
+ var routes = [];
+ for (var route in this.routes) {
+ routes.unshift([route, this.routes[route]]);
+ }
+ for (var i = 0, l = routes.length; i < l; i++) {
+ this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
+ }
+ },
+
+ // Convert a route string into a regular expression, suitable for matching
+ // against the current location hash.
+ _routeToRegExp: function(route) {
+ route = route.replace(escapeRegExp, '\\$&')
+ .replace(namedParam, '([^\/]+)')
+ .replace(splatParam, '(.*?)');
+ return new RegExp('^' + route + '$');
+ },
+
+ // Given a route, and a URL fragment that it matches, return the array of
+ // extracted parameters.
+ _extractParameters: function(route, fragment) {
+ return route.exec(fragment).slice(1);
+ }
+
+ });
+
+ // Backbone.History
+ // ----------------
+
+ // Handles cross-browser history management, based on URL fragments. If the
+ // browser does not support `onhashchange`, falls back to polling.
+ Backbone.History = function() {
+ this.handlers = [];
+ _.bindAll(this, 'checkUrl');
+ };
+
+ // Cached regex for cleaning leading hashes and slashes .
+ var routeStripper = /^[#\/]/;
+
+ // Cached regex for detecting MSIE.
+ var isExplorer = /msie [\w.]+/;
+
+ // Has the history handling already been started?
+ var historyStarted = false;
+
+ // Set up all inheritable **Backbone.History** properties and methods.
+ _.extend(Backbone.History.prototype, Backbone.Events, {
+
+ // The default interval to poll for hash changes, if necessary, is
+ // twenty times a second.
+ interval: 50,
+
+ // Get the cross-browser normalized URL fragment, either from the URL,
+ // the hash, or the override.
+ getFragment: function(fragment, forcePushState) {
+ if (fragment == null) {
+ if (this._hasPushState || forcePushState) {
+ fragment = window.location.pathname;
+ var search = window.location.search;
+ if (search) fragment += search;
+ } else {
+ fragment = window.location.hash;
+ }
+ }
+ fragment = decodeURIComponent(fragment.replace(routeStripper, ''));
+ if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
+ return fragment;
+ },
+
+ // Start the hash change handling, returning `true` if the current URL matches
+ // an existing route, and `false` otherwise.
+ start: function(options) {
+
+ // Figure out the initial configuration. Do we need an iframe?
+ // Is pushState desired ... is it available?
+ if (historyStarted) throw new Error("Backbone.history has already been started");
+ this.options = _.extend({}, {root: '/'}, this.options, options);
+ this._wantsHashChange = this.options.hashChange !== false;
+ this._wantsPushState = !!this.options.pushState;
+ this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);
+ var fragment = this.getFragment();
+ var docMode = document.documentMode;
+ var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
+ if (oldIE) {
+ this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
+ this.navigate(fragment);
+ }
+
+ // Depending on whether we're using pushState or hashes, and whether
+ // 'onhashchange' is supported, determine how we check the URL state.
+ if (this._hasPushState) {
+ $(window).bind('popstate', this.checkUrl);
+ } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
+ $(window).bind('hashchange', this.checkUrl);
+ } else if (this._wantsHashChange) {
+ this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
+ }
+
+ // Determine if we need to change the base url, for a pushState link
+ // opened by a non-pushState browser.
+ this.fragment = fragment;
+ historyStarted = true;
+ var loc = window.location;
+ var atRoot = loc.pathname == this.options.root;
+ if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
+ this.fragment = this.getFragment(null, true);
+ window.location.replace(this.options.root + '#' + this.fragment);
+ // Return immediately as browser will do redirect to new url
+ return true;
+ } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
+ this.fragment = loc.hash.replace(routeStripper, '');
+ window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
+ }
+
+ if (!this.options.silent) {
+ return this.loadUrl();
+ }
+ },
+
+ // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
+ // but possibly useful for unit testing Routers.
+ stop: function() {
+ $(window).unbind('popstate', this.checkUrl).unbind('hashchange', this.checkUrl);
+ clearInterval(this._checkUrlInterval);
+ historyStarted = false;
+ },
+
+ // Add a route to be tested when the fragment changes. Routes added later
+ // may override previous routes.
+ route: function(route, callback) {
+ this.handlers.unshift({route: route, callback: callback});
+ },
+
+ // Checks the current URL to see if it has changed, and if it has,
+ // calls `loadUrl`, normalizing across the hidden iframe.
+ checkUrl: function(e) {
+ var current = this.getFragment();
+ if (current == this.fragment && this.iframe) current = this.getFragment(this.iframe.location.hash);
+ if (current == this.fragment || current == decodeURIComponent(this.fragment)) return false;
+ if (this.iframe) this.navigate(current);
+ this.loadUrl() || this.loadUrl(window.location.hash);
+ },
+
+ // Attempt to load the current URL fragment. If a route succeeds with a
+ // match, returns `true`. If no defined routes matches the fragment,
+ // returns `false`.
+ loadUrl: function(fragmentOverride) {
+ var fragment = this.fragment = this.getFragment(fragmentOverride);
+ var matched = _.any(this.handlers, function(handler) {
+ if (handler.route.test(fragment)) {
+ handler.callback(fragment);
+ return true;
+ }
+ });
+ return matched;
+ },
+
+ // Save a fragment into the hash history, or replace the URL state if the
+ // 'replace' option is passed. You are responsible for properly URL-encoding
+ // the fragment in advance.
+ //
+ // The options object can contain `trigger: true` if you wish to have the
+ // route callback be fired (not usually desirable), or `replace: true`, if
+ // you which to modify the current URL without adding an entry to the history.
+ navigate: function(fragment, options) {
+ if (!historyStarted) return false;
+ if (!options || options === true) options = {trigger: options};
+ var frag = (fragment || '').replace(routeStripper, '');
+ if (this.fragment == frag || this.fragment == decodeURIComponent(frag)) return;
+ if (this._hasPushState) {
+ if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
+ this.fragment = frag;
+ window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, frag);
+ } else if (this._wantsHashChange) {
+ this.fragment = frag;
+ this._updateHash(window.location, frag, options.replace);
+ if (this.iframe && (frag != this.getFragment(this.iframe.location.hash))) {
+ // Opening and closing the iframe tricks IE7 and earlier to push a history entry on hash-tag change.
+ // When replace is true, we don't want this.
+ if(!options.replace) this.iframe.document.open().close();
+ this._updateHash(this.iframe.location, frag, options.replace);
+ }
+ } else {
+ window.location.assign(this.options.root + fragment);
+ }
+ if (options.trigger) this.loadUrl(fragment);
+ },
+
+ // Update the hash location, either replacing the current entry, or adding
+ // a new one to the browser history.
+ _updateHash: function(location, fragment, replace) {
+ if (replace) {
+ location.replace(location.toString().replace(/(javascript:|#).*$/, '') + '#' + fragment);
+ } else {
+ location.hash = fragment;
+ }
+ }
+ });
+
+ // Backbone.View
+ // -------------
+
+ // Creating a Backbone.View creates its initial element outside of the DOM,
+ // if an existing element is not provided...
+ Backbone.View = function(options) {
+ this.cid = _.uniqueId('view');
+ this._configure(options || {});
+ this._ensureElement();
+ this.initialize.apply(this, arguments);
+ this.delegateEvents();
+ };
+
+ // Cached regex to split keys for `delegate`.
+ var eventSplitter = /^(\S+)\s*(.*)$/;
+
+ // List of view options to be merged as properties.
+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
+
+ // Set up all inheritable **Backbone.View** properties and methods.
+ _.extend(Backbone.View.prototype, Backbone.Events, {
+
+ // The default `tagName` of a View's element is `"div"`.
+ tagName: 'div',
+
+ // jQuery delegate for element lookup, scoped to DOM elements within the
+ // current view. This should be prefered to global lookups where possible.
+ $: function(selector) {
+ return $(selector, this.el);
+ },
+
+ // Initialize is an empty function by default. Override it with your own
+ // initialization logic.
+ initialize: function(){},
+
+ // **render** is the core function that your view should override, in order
+ // to populate its element (`this.el`), with the appropriate HTML. The
+ // convention is for **render** to always return `this`.
+ render: function() {
+ return this;
+ },
+
+ // Remove this view from the DOM. Note that the view isn't present in the
+ // DOM by default, so calling this method may be a no-op.
+ remove: function() {
+ this.$el.remove();
+ return this;
+ },
+
+ // For small amounts of DOM Elements, where a full-blown template isn't
+ // needed, use **make** to manufacture elements, one at a time.
+ //
+ // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
+ //
+ make: function(tagName, attributes, content) {
+ var el = document.createElement(tagName);
+ if (attributes) $(el).attr(attributes);
+ if (content) $(el).html(content);
+ return el;
+ },
+
+ setElement: function(element, delegate) {
+ this.$el = $(element);
+ this.el = this.$el[0];
+ if (delegate !== false) this.delegateEvents();
+ },
+
+ // Set callbacks, where `this.events` is a hash of
+ //
+ // *{"event selector": "callback"}*
+ //
+ // {
+ // 'mousedown .title': 'edit',
+ // 'click .button': 'save'
+ // 'click .open': function(e) { ... }
+ // }
+ //
+ // pairs. Callbacks will be bound to the view, with `this` set properly.
+ // Uses event delegation for efficiency.
+ // Omitting the selector binds the event to `this.el`.
+ // This only works for delegate-able events: not `focus`, `blur`, and
+ // not `change`, `submit`, and `reset` in Internet Explorer.
+ delegateEvents: function(events) {
+ if (!(events || (events = getValue(this, 'events')))) return;
+ this.undelegateEvents();
+ for (var key in events) {
+ var method = events[key];
+ if (!_.isFunction(method)) method = this[events[key]];
+ if (!method) throw new Error('Event "' + events[key] + '" does not exist');
+ var match = key.match(eventSplitter);
+ var eventName = match[1], selector = match[2];
+ method = _.bind(method, this);
+ eventName += '.delegateEvents' + this.cid;
+ if (selector === '') {
+ this.$el.bind(eventName, method);
+ } else {
+ this.$el.delegate(selector, eventName, method);
+ }
+ }
+ },
+
+ // Clears all callbacks previously bound to the view with `delegateEvents`.
+ undelegateEvents: function() {
+ this.$el.unbind('.delegateEvents' + this.cid);
+ },
+
+ // Performs the initial configuration of a View with a set of options.
+ // Keys with special meaning *(model, collection, id, className)*, are
+ // attached directly to the view.
+ _configure: function(options) {
+ if (this.options) options = _.extend({}, this.options, options);
+ for (var i = 0, l = viewOptions.length; i < l; i++) {
+ var attr = viewOptions[i];
+ if (options[attr]) this[attr] = options[attr];
+ }
+ this.options = options;
+ },
+
+ // Ensure that the View has a DOM element to render into.
+ // If `this.el` is a string, pass it through `$()`, take the first
+ // matching element, and re-assign it to `el`. Otherwise, create
+ // an element from the `id`, `className` and `tagName` properties.
+ _ensureElement: function() {
+ if (!this.el) {
+ var attrs = getValue(this, 'attributes') || {};
+ if (this.id) attrs.id = this.id;
+ if (this.className) attrs['class'] = this.className;
+ this.setElement(this.make(this.tagName, attrs), false);
+ } else {
+ this.setElement(this.el, false);
+ }
+ }
+
+ });
+
+ // The self-propagating extend function that Backbone classes use.
+ var extend = function (protoProps, classProps) {
+ var child = inherits(this, protoProps, classProps);
+ child.extend = this.extend;
+ return child;
+ };
+
+ // Set up inheritance for the model, collection, and view.
+ Backbone.Model.extend = Backbone.Collection.extend =
+ Backbone.Router.extend = Backbone.View.extend = extend;
+
+ // Backbone.sync
+ // -------------
+
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
+ var methodMap = {
+ 'create': 'POST',
+ 'update': 'PUT',
+ 'delete': 'DELETE',
+ 'read': 'GET'
+ };
+
+ // Override this function to change the manner in which Backbone persists
+ // models to the server. You will be passed the type of request, and the
+ // model in question. By default, makes a RESTful Ajax request
+ // to the model's `url()`. Some possible customizations could be:
+ //
+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
+ // * Send up the models as XML instead of JSON.
+ // * Persist models via WebSockets instead of Ajax.
+ //
+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
+ // as `POST`, with a `_method` parameter containing the true HTTP method,
+ // as well as all requests with the body as `application/x-www-form-urlencoded`
+ // instead of `application/json` with the model in a param named `model`.
+ // Useful when interfacing with server-side languages like **PHP** that make
+ // it difficult to read the body of `PUT` requests.
+ Backbone.sync = function(method, model, options) {
+ var type = methodMap[method];
+
+ // Default JSON-request options.
+ var params = {type: type, dataType: 'json'};
+
+ // Ensure that we have a URL.
+ if (!options.url) {
+ params.url = getValue(model, 'url') || urlError();
+ }
+
+ // Ensure that we have the appropriate request data.
+ if (!options.data && model && (method == 'create' || method == 'update')) {
+ params.contentType = 'application/json';
+ params.data = JSON.stringify(model.toJSON());
+ }
+
+ // For older servers, emulate JSON by encoding the request into an HTML-form.
+ if (Backbone.emulateJSON) {
+ params.contentType = 'application/x-www-form-urlencoded';
+ params.data = params.data ? {model: params.data} : {};
+ }
+
+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
+ // And an `X-HTTP-Method-Override` header.
+ if (Backbone.emulateHTTP) {
+ if (type === 'PUT' || type === 'DELETE') {
+ if (Backbone.emulateJSON) params.data._method = type;
+ params.type = 'POST';
+ params.beforeSend = function(xhr) {
+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
+ };
+ }
+ }
+
+ // Don't process data on a non-GET request.
+ if (params.type !== 'GET' && !Backbone.emulateJSON) {
+ params.processData = false;
+ }
+
+ // Make the request, allowing the user to override any Ajax options.
+ return $.ajax(_.extend(params, options));
+ };
+
+ // Wrap an optional error callback with a fallback error event.
+ Backbone.wrapError = function(onError, originalModel, options) {
+ return function(model, resp) {
+ var resp = model === originalModel ? resp : model;
+ if (onError) {
+ onError(model, resp, options);
+ } else {
+ originalModel.trigger('error', model, resp, options);
+ }
+ };
+ };
+
+ // Helpers
+ // -------
+
+ // Shared empty constructor function to aid in prototype-chain creation.
+ var ctor = function(){};
+
+ // Helper function to correctly set up the prototype chain, for subclasses.
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
+ // class properties to be extended.
+ var inherits = function(parent, protoProps, staticProps) {
+ var child;
+
+ // The constructor function for the new subclass is either defined by you
+ // (the "constructor" property in your `extend` definition), or defaulted
+ // by us to simply call the parent's constructor.
+ if (protoProps && protoProps.hasOwnProperty('constructor')) {
+ child = protoProps.constructor;
+ } else {
+ child = function(){ parent.apply(this, arguments); };
+ }
+
+ // Inherit class (static) properties from parent.
+ _.extend(child, parent);
+
+ // Set the prototype chain to inherit from `parent`, without calling
+ // `parent`'s constructor function.
+ ctor.prototype = parent.prototype;
+ child.prototype = new ctor();
+
+ // Add prototype properties (instance properties) to the subclass,
+ // if supplied.
+ if (protoProps) _.extend(child.prototype, protoProps);
+
+ // Add static properties to the constructor function, if supplied.
+ if (staticProps) _.extend(child, staticProps);
+
+ // Correctly set child's `prototype.constructor`.
+ child.prototype.constructor = child;
+
+ // Set a convenience property in case the parent's prototype is needed later.
+ child.__super__ = parent.prototype;
+
+ return child;
+ };
+
+ // Helper function to get a value from a Backbone object as a property
+ // or as a function.
+ var getValue = function(object, prop) {
+ if (!(object && object[prop])) return null;
+ return _.isFunction(object[prop]) ? object[prop]() : object[prop];
+ };
+
+ // Throw an error when a URL is needed, and none is supplied.
+ var urlError = function() {
+ throw new Error('A "url" property or function must be specified');
+ };
+
+}).call(this);
View
BIN  option4_grails_mongo/web-app/destroy.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
311 option4_grails_mongo/web-app/todos.css
@@ -0,0 +1,311 @@
+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;
+}
+ #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 .todo-text {
+ 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);
+}
View
237 option4_grails_mongo/web-app/todos.js
@@ -0,0 +1,237 @@
+// An example Backbone application contributed by
+// [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple
+// [LocalStorage adapter](backbone-localstorage.html)
+// to persist Backbone models within your browser.
+
+// Load the application once the DOM is ready, using `jQuery.ready`:
+$(function(){
+
+ _.templateSettings = {
+ interpolate : /\{\{(.+?)\}\}/g,
+ evaluate : /\{!(.+?)!\}/g
+ };
+
+ // Todo Model
+ // ----------
+
+ // Our basic **Todo** model has `text`, `order`, and `done` attributes.
+ window.Todo = Backbone.Model.extend({
+
+ // Default attributes for a todo item.
+ defaults: function() {
+ return {
+ done: false,
+ order: Todos.nextOrder()
+ };
+ },
+
+ // Toggle the `done` state of this todo item.
+ toggle: function() {
+ this.save({done: !this.get("done")});
+ }
+
+ });
+
+ // Todo Collection
+ // ---------------
+
+ // The collection of todos is backed by *localStorage* instead of a remote
+ // server.
+ window.TodoList = Backbone.Collection.extend({
+
+ // Reference to this collection's model.
+ model: Todo,
+
+ url: '/todos',
+
+ // Filter down the list of all todo items that are finished.
+ done: function() {
+ return this.filter(function(todo){ return todo.get('done'); });
+ },
+
+ // Filter down the list to only todo items that are still not finished.
+ remaining: function() {
+ return this.without.apply(this, this.done());
+ },
+
+ // We keep the Todos in sequential order, despite being saved by unordered
+ // GUID in the database. This generates the next order number for new items.
+ nextOrder: function() {
+ if (!this.length) return 1;
+ return this.last().get('order') + 1;
+ },
+
+ // Todos are sorted by their original insertion order.
+ comparator: function(todo) {
+ return todo.get('order');
+ }
+
+ });
+
+ // Create our global collection of **Todos**.
+ window.Todos = new TodoList;
+
+ // Todo Item View
+ // --------------
+
+ // The DOM element for a todo item...
+ window.TodoView = Backbone.View.extend({
+
+ //... is a list tag.
+ tagName: "li",
+
+ // Cache the template function for a single item.
+ template: _.template($('#item-template').html()),
+
+ // The DOM events specific to an item.
+ events: {
+ "click .check" : "toggleDone",
+ "dblclick div.todo-text" : "edit",
+ "click span.todo-destroy" : "clear",
+ "keypress .todo-input" : "updateOnEnter"
+ },
+
+ // The TodoView listens for changes to its model, re-rendering.
+ initialize: function() {
+ this.model.bind('change', this.render, this);
+ this.model.bind('destroy', this.remove, this);
+ },
+
+ // Re-render the contents of the todo item.
+ render: function() {
+ $(this.el).html(this.template(this.model.toJSON()));
+ this.setText();
+ return this;
+ },
+
+ // To avoid XSS (not that it would be harmful in this particular app),
+ // we use `jQuery.text` to set the contents of the todo item.
+ setText: function() {
+ var text = this.model.get('text');
+ this.$('.todo-text').text(text);
+ this.input = this.$('.todo-input');
+ this.input.bind('blur', _.bind(this.close, this)).val(text);
+ },
+
+ // Toggle the `"done"` state of the model.
+ toggleDone: function() {
+ this.model.toggle();
+ },
+
+ // Switch this view into `"editing"` mode, displaying the input field.
+ edit: function() {
+ $(this.el).addClass("editing");
+ this.input.focus();
+ },
+
+ // Close the `"editing"` mode, saving changes to the todo.
+ close: function() {
+ this.model.save({text: this.input.val()});
+ $(this.el).removeClass("editing");
+ },
+
+ // If you hit `enter`, we're through editing the item.
+ updateOnEnter: function(e) {
+ if (e.keyCode == 13) this.close();
+ },
+
+ // Remove this view from the DOM.
+ remove: function() {
+ $(this.el).remove();
+ },
+
+ // Remove the item, destroy the model.
+ clear: function() {
+ this.model.destroy();
+ }
+
+ });
+
+ // The Application
+ // ---------------
+
+ // Our overall **AppView** is the top-level piece of UI.
+ window.AppView = Backbone.View.extend({
+
+ // Instead of generating a new element, bind to the existing skeleton of
+ // the App already present in the HTML.
+ el: $("#todoapp"),
+
+ // Our template for the line of statistics at the bottom of the app.
+ statsTemplate: _.template($('#stats-template').html()),
+
+ // Delegated events for creating new items, and clearing completed ones.
+ events: {
+ "keypress #new-todo": "createOnEnter",
+ "keyup #new-todo": "showTooltip",
+ "click .todo-clear a": "clearCompleted"
+ },
+
+ // At initialization we bind to the relevant events on the `Todos`
+ // collection, when items are added or changed. Kick things off by
+ // loading any preexisting todos that might be saved in *localStorage*.
+ initialize: function() {
+ this.input = this.$("#new-todo");
+
+ Todos.bind('add', this.addOne, this);
+ Todos.bind('reset', this.addAll, this);
+ Todos.bind('all', this.render, this);
+
+ Todos.fetch();
+ },
+
+ // Re-rendering the App just means refreshing the statistics -- the rest
+ // of the app doesn't change.
+ render: function() {
+ this.$('#todo-stats').html(this.statsTemplate({
+ total: Todos.length,
+ done: Todos.done().length,
+ remaining: Todos.remaining().length
+ }));
+ },
+
+ // Add a single todo item to the list by creating a view for it, and
+ // appending its element to the `<ul>`.
+ addOne: function(todo) {
+ var view = new TodoView({model: todo});
+ $("#todo-list").append(view.render().el);
+ },
+
+ // Add all items in the **Todos** collection at once.
+ addAll: function() {
+ Todos.each(this.addOne);
+ },
+
+ // If you hit return in the main input field, and there is text to save,
+ // create new **Todo** model persisting it to *localStorage*.
+ createOnEnter: function(e) {
+ var text = this.input.val();
+ if (!text || e.keyCode != 13) return;
+ Todos.create({text: text});
+ this.input.val('');
+ },
+
+ // Clear all done todo items, destroying their models.
+ clearCompleted: function() {
+ _.each(Todos.done(), function(todo){ todo.destroy(); });
+ return false;
+ },
+
+ // Lazily show the tooltip that tells you to press `enter` to save
+ // a new todo item, after one second.
+ showTooltip: function(e) {
+ var tooltip = this.$(".ui-tooltip-top");
+ var val = this.input.val();
+ tooltip.fadeOut();
+ if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
+ if (val == '' || val == this.input.attr('placeholder')) return;
+ var show = function(){ tooltip.show().fadeIn(); };
+ this.tooltipTimeout = _.delay(show, 1000);
+ }
+
+ });
+
+ // Finally, we kick things off by creating the **App**.
+ window.App = new AppView;
+
+});
View
999 option4_grails_mongo/web-app/underscore.js
@@ -0,0 +1,999 @@
+// Underscore.js 1.3.1
+// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
+// Underscore is freely distributable under the MIT license.
+// Portions of Underscore are inspired or borrowed from Prototype,
+// Oliver Steele's Functional, and John Resig's Micro-Templating.
+// For all details and documentation:
+// http://documentcloud.github.com/underscore
+
+(function() {
+
+ // Baseline setup
+ // --------------