Skip to content
Browse files

Initial commit

  • Loading branch information...
0 parents commit f6311f86113c6b9ad97086ac703791732411f762 @charly committed
Showing with 13,968 additions and 0 deletions.
  1. +6 −0 .gitignore
  2. +17 −0 Gemfile
  3. +20 −0 MIT-LICENSE
  4. +42 −0 README.md
  5. +39 −0 Rakefile
  6. +23 −0 backbonify.gemspec
  7. +79 −0 lib/assets/javascripts/backbone.filter.js
  8. +318 −0 lib/assets/javascripts/backbone.grid.js
  9. +1,143 −0 lib/assets/javascripts/backbone.js
  10. +21 −0 lib/assets/javascripts/backbone_datalink.js
  11. +68 −0 lib/assets/javascripts/backbone_rails_sync.js
  12. +131 −0 lib/assets/javascripts/formly.min.js
  13. +783 −0 lib/assets/javascripts/jquery-ui.js
  14. +9,266 −0 lib/assets/javascripts/jquery.js
  15. +79 −0 lib/assets/javascripts/jquery.notice.js
  16. +480 −0 lib/assets/javascripts/json2.js
  17. +981 −0 lib/assets/javascripts/underscore.js
  18. +4 −0 lib/backbonify.rb
  19. +5 −0 lib/backbonify/engine.rb
  20. +3 −0 lib/backbonify/version.rb
  21. +8 −0 lib/generators/backbonify/USAGE
  22. +29 −0 lib/generators/backbonify/hbs/hbs_generator.rb
  23. +6 −0 lib/generators/backbonify/hbs/templates/_form.haml
  24. +4 −0 lib/generators/backbonify/hbs/templates/_row.haml
  25. +1 −0 lib/generators/backbonify/hbs/templates/edit.haml
  26. +13 −0 lib/generators/backbonify/hbs/templates/index.haml
  27. +1 −0 lib/generators/backbonify/hbs/templates/new.haml
  28. +2 −0 lib/generators/backbonify/hbs/templates/page.haml
  29. +1 −0 lib/generators/backbonify/hbs/templates/show.haml
  30. +49 −0 lib/generators/backbonify/install/install_generator.rb
  31. +12 −0 lib/generators/backbonify/install/templates/app.js
  32. +20 −0 lib/generators/backbonify/model/model_generator.rb
  33. +21 −0 lib/generators/backbonify/model/templates/model.js
  34. +55 −0 lib/generators/backbonify/resource_helpers.rb
  35. +44 −0 lib/generators/backbonify/router/router_generator.rb
  36. +24 −0 lib/generators/backbonify/router/templates/router.js
  37. +2 −0 lib/generators/backbonify/router/templates/template.jst
  38. +8 −0 lib/generators/backbonify/router/templates/view.coffee
  39. +26 −0 lib/generators/backbonify/scaffold/scaffold_generator.rb
  40. +25 −0 lib/generators/backbonify/views/templates/edit_view.js
  41. +15 −0 lib/generators/backbonify/views/templates/index_view.js
  42. +26 −0 lib/generators/backbonify/views/templates/new_view.js
  43. +22 −0 lib/generators/backbonify/views/templates/page_view.js
  44. +19 −0 lib/generators/backbonify/views/templates/show_view.js
  45. +21 −0 lib/generators/backbonify/views/views_generator.rb
  46. +6 −0 script/rails
6 .gitignore
@@ -0,0 +1,6 @@
+.bundle/
+log/*.log
+pkg/
+test/dummy/db/*.sqlite3
+test/dummy/log/*.log
+test/dummy/tmp/
17 Gemfile
@@ -0,0 +1,17 @@
+source "http://rubygems.org"
+
+# Declare your gem's dependencies in backbonify.gemspec.
+# Bundler will treat runtime dependencies like base dependencies, and
+# development dependencies will be added by default to the :development group.
+gemspec
+
+# jquery-rails is used by the dummy application
+gem "jquery-rails"
+
+# Declare any dependencies that are still in development here instead of in
+# your gemspec. These might include edge Rails or gems from your path or
+# Git. Remember to move these dependencies to your gemspec before releasing
+# your gem to rubygems.org.
+
+# To use debugger
+# gem 'ruby-debug'
20 MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright 2011 Charles Sistovaris
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
42 README.md
@@ -0,0 +1,42 @@
+# Backbonify
+A generator for Backbone in Rails >= 3.1. The Language is javascript (no coffee)
+and the template engine is (only) handlebars wraped in haml! However this generator takes advantage of hooks (brought by yehuda in rails 3) so it is easy to add other template
+engines and so on...
+
+## Warning
+This is not a general purpose generator. I made it to fit my needs. And its quit beta.
+But hey it's just generators, not code...
+
+## Install with Rails 3.1
+In your Gemfile
+ gem "backbonify", :git => "http://github.com/charly/backbonify"
+
+## Usage
+In your console
+ rails g backbonify:install
+ rails g backbonify:scaffold Model field:type field:type
+
+## More Usage
+backbonify:scaffold hooks on those (sub) generators. You can also cherry pick them!
+ rails g backbonify:model Model field:type ...
+ rails g backbonify:router Model
+ rails g backbonify:view Model
+ rails g backbonify:template Model field:type ...
+
+## TODO
+test!!! options & more doc on what files it generates....
+
+## Dependencies for haml and handlebars
+Include them in your Gemfile
+ gem 'handlebars_assets'
+ gem 'haml_assets', :git => "http://github.com/infbio/haml_assets"
+
+
+## Thanks to
+Originally I wanted to fork [backbone-rails][1] to add javascript version
+(instead of cofeescript only). But it was too far a part.
+
+## License
+This project rocks and uses MIT-LICENSE.
+
+[1]: https://github.com/codebrew/backbone-rails
39 Rakefile
@@ -0,0 +1,39 @@
+#!/usr/bin/env rake
+begin
+ require 'bundler/setup'
+rescue LoadError
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
+end
+begin
+ require 'rdoc/task'
+rescue LoadError
+ require 'rdoc/rdoc'
+ require 'rake/rdoctask'
+ RDoc::Task = Rake::RDocTask
+end
+
+RDoc::Task.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'Backbonify'
+ rdoc.options << '--line-numbers'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
+load 'rails/tasks/engine.rake'
+
+
+Bundler::GemHelper.install_tasks
+
+require 'rake/testtask'
+
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = false
+end
+
+
+task :default => :test
23 backbonify.gemspec
@@ -0,0 +1,23 @@
+$:.push File.expand_path("../lib", __FILE__)
+
+# Maintain your gem's version:
+require "backbonify/version"
+
+# Describe your gem and declare its dependencies:
+Gem::Specification.new do |s|
+ s.name = "backbonify"
+ s.version = Backbonify::VERSION
+ s.authors = ["Charles Sistovaris"]
+ s.email = ["TODO: Your email"]
+ s.homepage = "http://ruby.simapse.com/"
+ s.summary = "Backbone Generator for Rails >= 3.1"
+ s.description = "TODO: Description of Backbonify."
+
+ s.files = Dir["{lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
+ s.test_files = Dir["test/**/*"]
+
+ s.add_dependency "rails", "~> 3.1"
+ # s.add_dependency "jquery-rails"
+
+ s.add_development_dependency "sqlite3"
+end
79 lib/assets/javascripts/backbone.filter.js
@@ -0,0 +1,79 @@
+// TODO : a mixin for pageViewfiltering
+//var pageViewfiltering = {
+// filter: function(event) {
+// if (event.which == 13) {
+// var a = this.getAttrValue(event)
+// this.collection.filterAttr(a[0], a[1])
+// }
+// },
+//
+// showLength:function() {
+// this.$("#collectionLength").text(this.collection.length)
+// },
+//
+// // helper to get the attr 'film' out of name='performance[film]'
+// getAttrValue: function(event) {
+// var $target = $(event.currentTarget),
+// query = $target.val(),
+// attr = $target.prop("name").replace(/[a-z_].*\[([a-z].*)\]/, "$1")
+// return [attr, query]
+// }
+//}
+
+
+var Filter = {
+ // ADD this in the collection
+ //initialize: function() {
+ // this._prepareFiltering();
+ //}
+
+ //
+ // FILTERING
+ //
+ _prepareFiltering: function() {
+ this.originalCollection = new Backbone.Collection;
+ this.previousCollection = new Backbone.Collection;
+ this.filterCollection = this;
+ this.bind("reset", this.setOriginalCollection, this)
+ },
+
+ //filterAttr("film", "city") instead of filterFilms("city")
+ filterAttr: function(attribute, query) {
+ this.handleFilters(attribute, query);
+
+ var reg = new RegExp(query,"i");
+ this.filtering(function(model){
+ var attrValue = model.get(attribute);
+ if(attrValue && attrValue.match(reg)) return model;
+ })
+ },
+
+ // previousCollection keeps track of the previous result so
+ // it can refilter on that one (it should be an array actually)
+ // TODO : consider having a filter for each attribute......
+ handleFilters: function(attribute, query) {
+ if(query == "") {
+ this.filterCollection = this.originalCollection
+ }
+ else if(this.previousAttr==attribute) {
+ this.filterCollection = this.previousCollection
+ }
+ else {
+ this.filterCollection = this;
+ }
+ this.previousCollection.reset(this.filterCollection.models);
+ this.previousAttr = attribute;
+ },
+
+ filtering: function(criteria) {
+ this.reset(this.filterCollection.select(criteria), {silent: true})
+ this.trigger("filter");
+ },
+
+ // loadedCollection is a copy of this collection to store
+ // the original models before they get filtered
+ setOriginalCollection: function(event) {
+ this.originalCollection.reset(this.models)
+ }
+
+}
318 lib/assets/javascripts/backbone.grid.js
@@ -0,0 +1,318 @@
+var Grid = {};
+
+// ===================================================
+// # PageView : fetches collections listens to newView
+// ===================================================
+// ## Main actions
+// -----------------
+// .render()
+// .refreshIndex() event :'change .submenu'
+// .addToIndex() event : 'reset' by a collection
+// .displayNew() event : 'click .submenu'
+//
+// ##Requirements (must be defined on 'host') :
+// --------------------------------------------
+// .indexView() : needs to be defined on host
+// .newView() : needs to be defined on host
+// data : property needs definition in host
+//
+Grid.PageView = function(options){
+ Backbone.View.apply(this, [options]);
+};
+
+_.extend(Grid.PageView.prototype, Backbone.View.prototype, {
+
+ render: function() {
+ $(this.el).html(this.template({length: this.collection.length}))
+ $(this.newView.render().el).hide().appendTo(this.el);
+ $(this.indexView.el).appendTo(this.el);
+ return this;
+ },
+
+ display: function() {
+ this.render();
+ $(this.el).hide();
+ $("#content").append(this.el)
+ this.slide()
+ },
+
+ slide: function() {
+ $(this.el).fadeIn("fast")
+ },
+
+ // Index View
+ refreshIndex : function(event) {
+ var year = $(event.currentTarget).prop("value");
+ this.indexView.collection.fetch({data: {year: year}})
+ },
+
+ // New View
+ displayNew : function(event){
+ event.preventDefault();
+ this.$(this.newView.el).slideToggle()
+ }
+
+});
+
+Grid.PageView.extend = Backbone.View.extend;
+
+
+// ==================================
+// # IndexView : rendered by PageView
+// ===================================
+//
+// ## Main Actions
+// ----------------
+// .render()
+//
+// ## Requirements
+// ----------------
+// collection
+// template
+//
+Grid.IndexView = function(options){
+ var events = {
+ "click tr[class!='edit'] td, tr[class!='month'] td" : "edit",
+ "mouseover tr" : "highlightStatus",
+ "mouseout tr" : "downlightStatus"
+ };
+
+ Backbone.View.apply(this, [options]);
+
+ this.delegateEvents(events);
+ this.collection.bind("reset", this.render, this);
+ this.collection.bind("add", this.render, this);
+ this.collection.bind("filter", this.render, this);
+};
+
+_.extend(Grid.IndexView.prototype, Backbone.View.prototype, {
+
+ render : function() {
+ var html = this.template({collection: this.collection.toJSON()});
+ $(this.el).html(html)
+ return this;
+ },
+
+ edit : function(event) {
+ this._setModelFromRow(event);
+ var p = new this.editView({model: this.model, el: this.row});
+ p.editCell(event);
+ },
+
+ // convienence method to extract the models id from tr#id
+ _setModelFromRow : function(event){
+ var $cell = this.$(event.currentTarget);
+ this.row = $cell.closest("tr");
+ this.row.addClass("edit");
+ var model_id = this.row.attr("id").replace(/[a-z].*_/, "");
+ this.model = this.collection.get(model_id);
+ },
+
+ highlightStatus: function(event) {
+ $(event.currentTarget).addClass("bgyellow")
+ },
+
+ downlightStatus: function(event) {
+ $(event.currentTarget).removeClass("bgyellow")
+ },
+
+ donothing: function() {}
+});
+
+Grid.IndexView.extend = Backbone.View.extend;
+
+
+
+// =====================================================
+// # NewView : handles displaying formtriggers 'created'
+// =====================================================
+//
+// ## Main actions
+// -----------------
+// .render()
+// .createModel() : 'submit'
+//
+// ## Requirements:
+// -------------------
+// _formHelpers() : needs to be defined on host
+// model property needs definition in host
+//
+Grid.NewView = function(options) {
+ var events = {
+ "submit": "createModel"
+ };
+
+ Backbone.View.apply(this, [options]);
+
+ this.delegateEvents(events);
+ if(this.collection) this.collection.bind("created", this.notifyCreated, this)
+ this.model.bind("error", this.notifyError, this);
+};
+
+_.extend(Grid.NewView.prototype, Backbone.View.prototype, {
+ // renders a nice form below the header
+ render: function(){
+ var html = this.template(this.model.toJSON());
+ $(this.el).html(html);
+ if(this._fomrHelpers) this._formHelpers();
+
+ return this;
+ },
+
+ // creates the performance from the form and adds it to collection
+ createModel: function(event) {
+ event.preventDefault();
+ var self = this, attrs = this.gatherInputs();
+ this.$("input[type='submit']").prop("disabled", true)
+
+ this.collection.create(attrs, {
+ success: function(){
+ self.collection.trigger("created", self.collection)
+ },
+ error: function() { self.notifyError() }
+ });
+ },
+
+ gatherInputs: function() {
+ var attrs = _.reduce(this.$("input[id],textarea"), function(memo, input){
+ var k = $(input).prop("name").replace(/[a-z_].*\[([a-z].*)\]/, "$1")
+ memo[k] = $(input).val() || $(input).text();
+ return memo;
+ }, {})
+ return attrs;
+ },
+
+ notifyCreated: function(collection) {
+ var self = this;
+ _.delay(function() {self.$("input[type='submit']").prop("disabled", false)}, 3000)
+ $.noticeAdd({text: "Succesfully created, Yo!"})
+ },
+
+ notifyError: function(collection) {
+ _.delay(function() {self.$("input[type='submit']").prop("disabled", false)}, 3000)
+ $.noticeAdd({text: "Error yo, put a date or a film or something"})
+ }
+
+});
+
+Grid.NewView.extend = Backbone.View.extend;
+
+
+// ====================================================
+// # EditView : opens an input on a the dblclicked cell
+// ====================================================
+//
+// ## Main Actions
+// -----------------
+// .editCell() : "dblclick td"
+// .updateModel() => REFACTOR !!!!!!
+//
+// ## Requirements (must be defined on 'host') :
+// -----------------------------------------------
+// _formHelpers() : extra stuff like jquery-ui stuff
+//
+Grid.EditView = function(options) {
+
+ var events = {
+ "click input,textarea" : "donothing",
+ "dblclick input,textarea" : "donothing",
+ "click td" : "editCell",
+ "keypress input,textarea" : "keypress",
+ "keyup input,textarea" : "keypress"
+ };
+
+ Backbone.View.apply(this, [options]);
+
+ this.delegateEvents(events);
+
+};
+
+_.extend(Grid.EditView.prototype, Backbone.View.prototype, {
+
+
+ editCell : function(event) {
+ event.stopImmediatePropagation();
+ this.cell = $(event.currentTarget);
+ this.attribute = this.cell.attr("class");
+
+ var inputTemplate = this._createInputTemplate();
+ if(inputTemplate == false) return;
+ var template = Handlebars.compile(inputTemplate);
+ this.inputTag = template( this.model.toJSON() );
+
+ // setting height & width
+ var width = this._cellWidth();
+ var height = this._cellHeight();
+ if( $(this.inputTag).prop("type") != "checkbox" ){
+ this.inputTag = $(this.inputTag).width(width - 10);
+ //this.inputTag = $(this.inputTag).height(height - 6);
+ }
+
+ // renders the input tag
+ this.cell.html(this.inputTag);
+ $(this.inputTag).focus();
+
+ this._formHelpers()
+ this._orchestrasAutocomplete();
+
+ return this;
+ },
+
+ // calculates cell width so it can be applied on the input tag
+ _cellWidth : function() {
+ var width = this.cell.width();
+ this.cell.width(width);
+ return width;
+ },
+
+ _cellHeight : function(){
+ var height = this.cell.height();
+ //this.cell.height(height);
+ return height
+ },
+
+ gatherInputs: function() {
+ var attrs = _.reduce(this.$("input,textarea"), function(memo, input){
+ memo[$(input).attr("name")] = $(input).val() || $(input).text();
+ return memo;
+ }, {})
+ return attrs;
+ },
+
+ // gathers all the inputs tag of a row and sets the attributes of the model
+ updateModel : function() {
+ var self = this,
+ attrs = this.gatherInputs()
+ this.model.save(attrs, {
+ success: function() { self.renderRow(); self.model.trigger("saved"); },
+ error: function() { alert("error") }
+ });
+ },
+
+ // renders a clean row after an update (or a create ?)
+ renderRow : function(){
+ var html = this.template(this.model.toJSON());
+ $(this.el).html(html);
+ },
+
+ // just a wrapper to call updateModel
+ keypress: function (event) {
+ if (event.which == 13) { // retrun
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ this.updateModel();
+ } else if (event.which == 27) { // escape
+ event.stopImmediatePropagation();
+ this.renderRow();
+ }
+ },
+
+ donothing : function(event) {
+ event.stopImmediatePropagation();
+ },
+
+ noop: null
+});
+
+Grid.EditView.extend = Backbone.View.extend;
+
1,143 lib/assets/javascripts/backbone.js
@@ -0,0 +1,1143 @@
+// Backbone.js 0.5.3
+// (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.
+// Backbone may be freely distributed under the MIT license.
+// For all details and documentation:
+// http://documentcloud.github.com/backbone
+
+(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.
+ var slice = Array.prototype.slice;
+
+ // 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` or `unbind` a callback function to an event;
+ // `trigger`-ing an event fires all callbacks in succession.
+ //
+ // var object = {};
+ // _.extend(object, Backbone.Events);
+ // object.bind('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.
+ bind : function(ev, callback, context) {
+ var calls = this._callbacks || (this._callbacks = {});
+ 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 `callback` is null, removes all
+ // callbacks for the event. If `ev` is null, removes all bound callbacks
+ // for all events.
+ unbind : function(ev, callback) {
+ var calls, node, prev;
+ if (!ev) {
+ this._callbacks = null;
+ } else if (calls = this._callbacks) {
+ if (!callback) {
+ calls[ev] = {};
+ } else if (node = calls[ev]) {
+ while ((prev = node) && (node = node.next)) {
+ if (node.callback !== callback) continue;
+ prev.next = node.next;
+ node.context = node.callback = null;
+ break;
+ }
+ }
+ }
+ 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(eventName) {
+ var node, calls, callback, args, ev, events = ['all', eventName];
+ if (!(calls = this._callbacks)) return this;
+ while (ev = events.pop()) {
+ if (!(node = calls[ev])) continue;
+ args = ev == 'all' ? arguments : slice.call(arguments, 1);
+ while (node = node.next) if (callback = node.callback) callback.apply(node.context || this, args);
+ }
+ return this;
+ }
+
+ };
+
+ // 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 = this.defaults) {
+ if (_.isFunction(defaults)) defaults = defaults.call(this);
+ attributes = _.extend({}, defaults, attributes);
+ }
+ this.attributes = {};
+ this._escapedAttributes = {};
+ this.cid = _.uniqueId('c');
+ this.set(attributes, {silent : true});
+ this._changed = false;
+ this._previousAttributes = _.clone(this.attributes);
+ if (options && options.collection) this.collection = options.collection;
+ this.initialize(attributes, options);
+ };
+
+ // 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;
+ if (_.isObject(key)) {
+ attrs = key;
+ options = value;
+ } else {
+ attrs = {};
+ attrs[key] = value;
+ }
+
+ // Extract attributes and options.
+ options || (options = {});
+ if (!attrs) return this;
+ if (attrs.attributes) 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 (!options.silent && 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.
+ for (var attr in attrs) {
+ var val = attrs[attr];
+ if (!_.isEqual(now[attr], val) || (options.unset && (attr in now))) {
+ options.unset ? delete now[attr] : now[attr] = val;
+ delete escaped[attr];
+ this._changed = true;
+ if (!options.silent) this.trigger('change:' + attr, this, val, 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 = {});
+ 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 = 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(attrs, options) {
+ options || (options = {});
+ if (attrs && !this.set(attrs, options)) return false;
+ 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, xhr);
+ };
+ options.error = 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. Upon success, the model is removed
+ // from its collection, if it has one.
+ destroy : function(options) {
+ options || (options = {});
+ if (this.isNew()) return this.trigger('destroy', this, this.collection, options);
+ var model = this;
+ var success = options.success;
+ options.success = function(resp) {
+ model.trigger('destroy', model, model.collection, options);
+ if (success) success(model, resp);
+ };
+ options.error = wrapError(options.error, model, options);
+ return (this.sync || Backbone.sync).call(this, 'delete', this, options);
+ },
+
+ // 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 = getUrl(this.collection) || 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);
+ },
+
+ // 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 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 error = this.validate(attrs, 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;
+ _.bindAll(this, '_onModelEvent', '_removeReference');
+ this._reset();
+ if (models) this.reset(models, {silent: true});
+ this.initialize.apply(this, arguments);
+ };
+
+ // 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 `added` event for every new model.
+ add : function(models, options) {
+ if (_.isArray(models)) {
+ for (var i = 0, l = models.length; i < l; i++) {
+ this._add(models[i], options);
+ }
+ } else {
+ this._add(models, options);
+ }
+ return this;
+ },
+
+ // Remove a model, or a list of models from the set. Pass silent to avoid
+ // firing the `removed` event for every model removed.
+ remove : function(models, options) {
+ if (_.isArray(models)) {
+ for (var i = 0, l = models.length; i < l; i++) {
+ this._remove(models[i], options);
+ }
+ } else {
+ this._remove(models, options);
+ }
+ 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');
+ this.models = this.sortBy(this.comparator);
+ 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 `added` or `removed` events. Fires `reset` when finished.
+ reset : function(models, options) {
+ models || (models = []);
+ options || (options = {});
+ this.each(this._removeReference);
+ 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 = {});
+ 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 = 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. After the model
+ // has been created on the server, it will be added to the collection.
+ // Returns the model, or 'false' if validation on a new model fails.
+ create : function(model, options) {
+ var coll = this;
+ options || (options = {});
+ model = this._prepareModel(model, options);
+ if (!model) return false;
+ var success = options.success;
+ options.success = function(nextModel, resp, xhr) {
+ coll.add(nextModel, options);
+ if (success) success(nextModel, resp, xhr);
+ };
+ 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;
+ model = new this.model(attrs, {collection: this, parse: options.parse});
+ if (model.validate && !model._performValidation(model.attributes, options)) model = false;
+ } else if (!model.collection) {
+ model.collection = this;
+ }
+ return model;
+ },
+
+ // Internal implementation of adding a single model to the set, updating
+ // hash indexes for `id` and `cid` lookups.
+ // Returns the model, or 'false' if validation on a new model fails.
+ _add : function(model, options) {
+ options || (options = {});
+ model = this._prepareModel(model, options);
+ if (!model) return false;
+ var already = this.getByCid(model);
+ if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
+ this._byId[model.id] = model;
+ this._byCid[model.cid] = model;
+ var index = options.at != null ? options.at :
+ this.comparator ? this.sortedIndex(model, this.comparator) :
+ this.length;
+ this.models.splice(index, 0, model);
+ model.bind('all', this._onModelEvent);
+ this.length++;
+ options.index = index;
+ if (!options.silent) model.trigger('add', model, this, options);
+ return model;
+ },
+
+ // Internal implementation of removing a single model from the set, updating
+ // hash indexes for `id` and `cid` lookups.
+ _remove : function(model, options) {
+ options || (options = {});
+ model = this.getByCid(model) || this.get(model);
+ if (!model) return null;
+ delete this._byId[model.id];
+ delete this._byCid[model.cid];
+ var index = this.indexOf(model);
+ this.models.splice(index, 1);
+ this.length--;
+ options.index = index;
+ if (!options.silent) model.trigger('remove', model, this, options);
+ this._removeReference(model);
+ return model;
+ },
+
+ // Internal method to remove a model's ties to a collection.
+ _removeReference : function(model) {
+ if (this == model.collection) {
+ delete model.collection;
+ }
+ model.unbind('all', this._onModelEvent);
+ },
+
+ // 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', 'rest', 'last', 'without', 'indexOf', '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\d]+)/g;
+ var splatParam = /\*([\w\d]+)/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);
+ 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));
+ }, 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 hashes.
+ var hashStrip = /^#/;
+
+ // 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, {
+
+ // 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(hashStrip, ''));
+ 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._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 ('onhashchange' in window && !oldIE) {
+ $(window).bind('hashchange', this.checkUrl);
+ } else {
+ 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._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(hashStrip, '');
+ window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
+ }
+
+ if (!this.options.silent) {
+ return this.loadUrl();
+ }
+ },
+
+ // 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 (!options || options === true) options = {trigger: options};
+ var frag = (fragment || '').replace(hashStrip, '');
+ 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 {
+ 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);
+ }
+ }
+ 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.delegateEvents();
+ this.initialize.apply(this, arguments);
+ };
+
+ // 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 == null) ? $(this.el) : $(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;
+ },
+
+ // Set callbacks, where `this.events` is a hash of
+ //
+ // *{"event selector": "callback"}*
+ //
+ // {
+ // 'mousedown .title': 'edit',
+ // 'click .button': 'save'
+ // }
+ //
+ // 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 = this.events))) return;
+ if (_.isFunction(events)) events = events.call(this);
+ this.undelegateEvents();
+ for (var key in events) {
+ var 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 = this.attributes || {};
+ if (this.id) attrs.id = this.id;
+ if (this.className) attrs['class'] = this.className;
+ this.el = this.make(this.tagName, attrs);
+ } else if (_.isString(this.el)) {
+ this.el = $(this.el).get(0);
+ }
+ }
+
+ });
+
+ // 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;
+
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
+ var methodMap = {
+ 'create': 'POST',
+ 'update': 'PUT',
+ 'delete': 'DELETE',
+ 'read' : 'GET'
+ };
+
+ // Backbone.sync
+ // -------------
+
+ // 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 = getUrl(model) || 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));
+ };
+
+ // 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 `super()`.
+ if (protoProps && protoProps.hasOwnProperty('constructor')) {
+ child = protoProps.constructor;
+ } else {
+ child = function(){ return 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 URL from a Model or Collection as a property
+ // or as a function.
+ var getUrl = function(object) {
+ if (!(object && object.url)) return null;
+ return _.isFunction(object.url) ? object.url() : object.url;
+ };
+
+ // 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');
+ };
+
+ // Wrap an optional error callback with a fallback error event.
+ var 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);
+ }
+ };
+ };
+
+}).call(this);
21 lib/assets/javascripts/backbone_datalink.js
@@ -0,0 +1,21 @@
+(function($) {
+ return $.extend($.fn, {
+ backboneLink: function(model) {
+ return $(this).find(":input").each(function() {
+ var el, name;
+ el = $(this);
+ name = el.attr("name");
+ model.bind("change:" + name, function() {
+ return el.val(model.get(name));
+ });
+ return $(this).bind("change", function() {
+ var attrs;
+ el = $(this);
+ attrs = {};
+ attrs[el.attr("name")] = el.val();
+ return model.set(attrs);
+ });
+ });
+ }
+ });
+})(jQuery);
68 lib/assets/javascripts/backbone_rails_sync.js
@@ -0,0 +1,68 @@
+(function() {
+ var methodMap = {
+ 'create': 'POST',
+ 'update': 'PUT',
+ 'delete': 'DELETE',
+ 'read' : 'GET'
+ };
+
+ var getUrl = function(object) {
+ if (!(object && object.url)) return null;
+ return _.isFunction(object.url) ? object.url() : object.url;
+ };
+
+ var urlError = function() {
+ throw new Error("A 'url' property or function must be specified");
+ };
+
+ Backbone.sync = function(method, model, options) {
+ var type = methodMap[method];
+
+ // Default JSON-request options.
+ var params = _.extend({
+ type: type,
+ dataType: 'json',
+ beforeSend: function( xhr ) {
+ var token = $('meta[name="csrf-token"]').attr('content');
+ if (token) xhr.setRequestHeader('X-CSRF-Token', token);
+
+ model.trigger('sync:start');
+ }
+ }, options);
+
+ if (!params.url) {
+ params.url = getUrl(model) || urlError();
+ }
+
+ // Ensure that we have the appropriate request data.
+ if (!params.data && model && (method == 'create' || method == 'update')) {
+ params.contentType = 'application/json';
+
+ var data = {}
+
+ if(model.paramRoot) {
+ data[model.paramRoot] = model.toJSON();
+ } else {
+ data = model.toJSON();
+ }
+
+ params.data = JSON.stringify(data)
+ }
+
+ // Don't process data on a non-GET request.
+ if (params.type !== 'GET') {
+ params.processData = false;
+ }
+
+ // Trigger the sync end event
+ var complete = options.complete;
+ params.complete = function(jqXHR, textStatus) {
+ model.trigger('sync:end');
+ if (complete) complete(jqXHR, textStatus);
+ };
+
+ // Make the request.
+ return $.ajax(params);
+ }
+
+}).call(this);
131 lib/assets/javascripts/formly.min.js
@@ -0,0 +1,131 @@
+(function($)
+{$.fn.formly=function(options,callback)
+{var settings={'theme':'Base','onBlur':true};if(options)
+{$.extend(settings,options);}
+var formName=this.attr('id');if(!formName)
+{formName=Math.ceil(Math.random()*5000);this.attr('id',formName);}
+this.append('<div style="clear:both;"></div><div class="formlyAlerts"></div>');this.addClass('formlyWrapper-'+settings['theme']);if(this.attr('width'))
+{this.css('width',this.attr('width'));}
+if(this.attr('subtitle')||this.attr('title'))
+{this.prepend('<hr/>');}
+if(this.attr('subtitle'))
+{this.prepend('<h2>'+this.attr('subtitle')+'</h2>');}
+if(this.attr('title'))
+{this.prepend('<h1>'+this.attr('title')+'</h1>');}
+this.children().each(function(index,item)
+{if($(item).attr('place'))
+{if($(item).attr('type')=='password')
+{var hID='pwPlace-'+$(item).attr('name');$(item).after('<input type="text" id="'+hID+'" value="'+$(item).attr('place')+'" class="formlyPWPlaces" />');$('#'+hID).css('color','#bbb');$(item).hide();$('#'+hID).show();$('#'+hID).focus(function()
+{$('#'+hID).hide();$(item).show();$(item).focus();});$(item).blur(function()
+{if(!$(item).val())
+{$('#'+hID).show();$(item).hide();}});}
+else
+{$(item).val($(item).attr('place'));$(item).css('color','#bbb');}}
+$(item).blur(function()
+{if(!$(item).val()||$(item).val()==$(item).attr('pre-fix'))
+{if($(item).attr('type')!='password')
+{$(item).val($(item).attr('place'));$(item).css('color','#bbb');}}
+if($(item).attr('pre-fix'))
+{var originalVal=$(item).val();var thePrefix=$(item).attr('pre-fix');if(thePrefix.length==1)
+{if(originalVal.charAt(0)!=thePrefix&&$(item).val()!=$(item).attr('place'))
+{$(item).val(thePrefix+originalVal);}}
+else
+{if(originalVal.indexOf(thePrefix)==-1&&$(item).val()!=$(item).attr('place'))
+{$(item).val(thePrefix+originalVal);}}}
+if(settings['onBlur'])
+{if($(item).attr('validate'))
+{functions.validate(item);}
+if($(item).attr('require'))
+{functions.require(item);}
+if($(item).attr('match'))
+{functions.match(item);}}});$(item).focus(function()
+{if($(item).attr('place'))
+{if($(item).val()==$(item).attr('place'))
+{$(item).val('');$(item).css('color','');}}
+if($(item).attr('pre-fix')&&!$(item).val())
+{$(item).val('');$(item).val($(item).attr('pre-fix'));}});$('#'+formName).find('input:reset').click(function(item)
+{item.preventDefault();$('#'+formName).find('input:text, input:password, input:checkbox, input:radio').each(function()
+{$(this).css('border-color','');if($(this).is(':checked'))
+{$(this).attr('checked',false);}
+if($(this).attr('place'))
+{if($(this).attr('type')!='password')
+{$(this).val($(this).attr('place'));$(this).css('color','#bbb');}
+else
+{if($(this).hasClass('formlyPWPlaces'))
+{$(this).show();$(this).prev('input').hide();}
+else
+{$(this).val('');}}}
+else
+{if($(this).hasClass('formlyPWPlaces'))
+{$(this).show();$(this).prev('input').hide();}
+else
+{$(this).val('');}}});$('#'+formName).find('.formlyAlert').each(function()
+{$(this).fadeOut(function()
+{$(this).remove()});});});});this.submit(function(item)
+{var canSubmit=true;$(this).find('input').each(function()
+{if($(this).attr('require'))
+{if(!functions.require(this))
+{canSubmit=false;}}
+if($(this).attr('validate'))
+{if(!functions.validate(this))
+{canSubmit=false;}}
+if($(this).attr('match'))
+{if(!functions.match(this))
+{canSubmit=false;}}});if(!canSubmit)
+{item.preventDefault();}
+else
+{if(callback)
+{item.preventDefault();callback($(this).serialize());}}});var functions={validateString:function(type,string)
+{if(type=='email')
+{var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
+if(filter.test(string))
+{return true;}
+else
+{return false;}}
+else if(type=='http')
+{var filter=/http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,3}/i
+if(filter.test(string))
+{return true;}
+else
+{return false;}}},validate:function(item)
+{var alertName=formName+$(item).attr('name');if($(item).attr('validate')=='email')
+{var valid=functions.validateString('email',$(item).val());var validType='email address';}
+else if($(item).attr('validate')=='http')
+{var valid=functions.validateString('http',$(item).val());var validType='web address';}
+if(!valid)
+{if(!$('#'+alertName).is(':visible'))
+{$('#'+formName).find('.formlyAlerts').append('<div class="formlyInvalid formlyAlert" id="'+alertName+'">Invalid '+validType+'</div>')
+$('#'+alertName).fadeIn();}
+var borderColor=$('#'+alertName).css('background-color');$(item).css('border-color',borderColor);if($(item).attr('type')=='password')
+{$(item).next('.formlyPWPlaces').css('border-color',borderColor);}
+return false;}
+else
+{$('#'+alertName).fadeOut(function()
+{$(this).remove()});$(item).css('border-color','');$('.formlyPWPlaces').css('border-color','');return true;}},require:function(item)
+{var alertName=formName+$(item).attr('name');var label=$(item).attr('label')+' ';if(label=='undefined '){label='';}
+if(!$(item).val()||$(item).val()==$(item).attr('place'))
+{if(!$('#'+alertName).is(':visible'))
+{$('#'+formName).find('.formlyAlerts').append('<div class="formlyRequired formlyAlert" id="'+alertName+'">'+label+'Required</div>')
+$('#'+alertName).fadeIn();}
+var borderColor=$('#'+alertName).css('background-color');$(item).css('border-color',borderColor);if($(item).attr('type')=='password')
+{$(item).next('.formlyPWPlaces').css('border-color',borderColor);}
+return false;}
+else if($(item).attr('type')=='checkbox'&&!$(item).is(':checked'))
+{if(!$('#'+alertName).is(':visible'))
+{$('#'+formName).find('.formlyAlerts').append('<div class="formlyRequired formlyAlert" id="'+alertName+'">'+label+'Required</div>')
+$('#'+alertName).fadeIn();$(item).focus();}
+var borderColor=$('#'+alertName).css('background-color');$(item).css('border-color',borderColor);return false;}
+else
+{$('#'+alertName).fadeOut(function()
+{$(this).remove()});$(item).css('border-color','');$('.formlyPWPlaces').css('border-color','');return true;}},match:function(item)
+{var alertName=formName+$(item).attr('name');var label=$(item).attr('label')+' ';if(label=='undefined '){label='';}
+var toMatch=$(item).attr('match');if($(item).val()!=$('#'+formName).find('input[name='+toMatch+']').val()||!$(item).val())
+{if(!$('#'+alertName).is(':visible'))
+{$('#'+formName).find('.formlyAlerts').append('<div class="formlyInvalid formlyAlert" id="'+alertName+'">'+label+'Does not match</div>')
+$('#'+alertName).fadeIn();}
+var borderColor=$('#'+alertName).css('background-color');$(item).css('border-color',borderColor);if($(item).attr('type')=='password')
+{$(item).next('.formlyPWPlaces').css('border-color',borderColor);}
+return false;}
+else
+{$('#'+alertName).fadeOut(function()
+{$(this).remove()});$(item).css('border-color','');$('.formlyPWPlaces').css('border-color','');return true;}}};};})(jQuery);
783 lib/assets/javascripts/jquery-ui.js
783 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
9,266 lib/assets/javascripts/jquery.js
9,266 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
79 lib/assets/javascripts/jquery.notice.js
@@ -0,0 +1,79 @@
+/**
+* jQuery.noticeAdd() and jQuery.noticeRemove()
+* These functions create and remove growl-like notices
+*
+* Copyright (c) 2009 Tim Benniks
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy
+* of this software and associated documentation files (the "Software"), to deal
+* in the Software without restriction, including without limitation the rights
+* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+* copies of the Software, and to permit persons to whom the Software is
+* furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in
+* all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+* THE SOFTWARE.
+*
+* @author Tim Benniks <tim@timbenniks.com>
+* @copyright 2009 timbenniks.com
+* @version $Id: jquery.notice.js 1 2009-01-24 12:24:18Z timbenniks $
+**/
+(function(jQuery)
+{
+ jQuery.extend({
+ noticeAdd: function(options)
+ {
+ var defaults = {
+ inEffect: {opacity: 'show'}, // in effect
+ inEffectDuration: 600, // in effect duration in miliseconds
+ stayTime: 3000, // time in miliseconds before the item has to disappear
+ text: '', // content of the item
+ stay: false, // should the notice item stay or not?
+ type: 'notice' // could also be error, succes
+ }
+
+ // declare varaibles
+ var options, noticeWrapAll, noticeItemOuter, noticeItemInner, noticeItemClose;
+
+ options = jQuery.extend({}, defaults, options);
+ noticeWrapAll = (!jQuery('.notice-wrap').length) ? jQuery('<div></div>').addClass('notice-wrap').appendTo('body') : jQuery('.notice-wrap');
+ noticeItemOuter = jQuery('<div></div>').addClass('notice-item-wrapper');
+ noticeItemInner = jQuery('<div></div>').hide().addClass('notice-item ' + options.type).appendTo(noticeWrapAll).html('<p>'+options.text+'</p>').animate(options.inEffect, options.inEffectDuration).wrap(noticeItemOuter);
+ noticeItemClose = jQuery('<div></div>').addClass('notice-item-close').prependTo(noticeItemInner).html('x').click(function() { jQuery.noticeRemove(noticeItemInner) });
+
+ // hmmmz, zucht
+ if(navigator.userAgent.match(/MSIE 6/i))
+ {
+ noticeWrapAll.css({top: document.documentElement.scrollTop});
+ }
+
+ if(!options.stay)
+ {
+ setTimeout(function()
+ {
+ jQuery.noticeRemove(noticeItemInner);
+ },
+ options.stayTime);
+ }
+ },
+
+ noticeRemove: function(obj)
+ {
+ obj.animate({opacity: '0'}, 600, function()
+ {
+ obj.parent().animate({height: '0px'}, 300, function()
+ {
+ obj.parent().remove();
+ });
+ });
+ }
+ });
+})(jQuery);
480 lib/assets/javascripts/json2.js
@@ -0,0 +1,480 @@
+/*
+ http://www.JSON.org/json2.js
+ 2011-02-23
+
+ Public Domain.
+
+ NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+
+ See http://www.JSON.org/js.html
+
+
+ This code should be minified before deployment.
+ See http://javascript.crockford.com/jsmin.html
+
+ USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
+ NOT CONTROL.
+
+
+ This file creates a global JSON object containing two methods: stringify
+ and parse.
+
+ JSON.stringify(value, replacer, space)
+ value any JavaScript value, usually an object or array.
+
+ replacer an optional parameter that determines how object
+ values are stringified for objects. It can be a
+ function or an array of strings.
+
+ space an optional parameter that specifies the indentation
+ of nested structures. If it is omitted, the text will
+ be packed without extra whitespace. If it is a number,
+ it will specify the number of spaces to indent at each
+ level. If it is a string (such as '\t' or '&nbsp;'),
+ it contains the characters used to indent at each level.
+
+ This method produces a JSON text from a JavaScript value.
+
+ When an object value is found, if the object contains a toJSON
+ method, its toJSON method will be called and the result will be
+ stringified. A toJSON method does not serialize: it returns the
+ value represented by the name/value pair that should be serialized,
+ or undefined if nothing should be serialized. The toJSON method
+ will be passed the key associated with the value, and this will be
+ bound to the value
+
+ For example, this would serialize Dates as ISO strings.
+
+ Date.prototype.toJSON = function (key) {
+ function f(n) {
+ // Format integers to have at least two digits.
+ return n < 10 ? '0' + n : n;
+ }
+
+ return this.getUTCFullYear() + '-' +
+ f(this.getUTCMonth() + 1) + '-' +
+ f(this.getUTCDate()) + 'T' +
+ f(this.getUTCHours()) + ':' +
+ f(this.getUTCMinutes()) + ':' +
+ f(this.getUTCSeconds()) + 'Z';
+ };
+
+ You can provide an optional replacer method. It will be passed the
+ key and value of each member, with this bound to the containing
+ object. The value that is returned from your method will be
+ serialized. If your method returns undefined, then the member will
+ be excluded from the serialization.
+
+ If the replacer parameter is an array of strings, then it will be
+ used to select the members to be serialized. It filters the results
+ such that only members with keys listed in the replacer array are
+ stringified.
+
+ Values that do not have JSON representations, such as undefined or
+ functions, will not be serialized. Such values in objects will be
+ dropped; in arrays they will be replaced with null. You can use
+ a replacer function to replace those with JSON values.
+ JSON.stringify(undefined) returns undefined.
+
+ The optional space parameter produces a stringification of the
+ value that is filled with line breaks and indentation to make it
+ easier to read.
+
+ If the space parameter is a non-empty string, then that string will
+ be used for indentation. If the space parameter is a number, then
+ the indentation will be that many spaces.
+
+ Example:
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}]);
+ // text is '["e",{"pluribus":"unum"}]'
+
+
+ text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
+ // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
+
+ text = JSON.stringify([new Date()], function (key, value) {
+ return this[key] instanceof Date ?
+ 'Date(' + this[key] + ')' : value;
+ });
+ // text is '["Date(---current time---)"]'
+
+
+ JSON.parse(text, reviver)
+ This method parses a JSON text to produce an object or array.
+ It can throw a SyntaxError exception.
+
+ The optional reviver parameter is a function that can filter and
+ transform the results. It receives each of the keys and values,
+ and its return value is used instead of the original value.
+ If it returns what it received, then the structure is not modified.
+ If it returns undefined then the member is deleted.
+
+ Example:
+
+ // Parse the text. Values that look like ISO date strings will
+ // be converted to Date objects.
+
+ myData = JSON.parse(text, function (key, value) {
+ var a;
+ if (typeof value === 'string') {
+ a =
+/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
+ if (a) {
+ return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+ +a[5], +a[6]));
+ }
+ }
+ return value;
+ });
+
+ myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
+ var d;
+ if (typeof value === 'string' &&
+ value.slice(0, 5) === 'Date(' &&
+ value.slice(-1) === ')') {
+ d = new Date(value.slice(5, -1));
+ if (d) {
+ return d;
+ }
+ }
+ return value;
+ });
+
+
+ This is a reference implementation. You are free to copy, modify, or
+ redistribute.
+*/
+
+/*jslint evil: true, strict: false, regexp: false */
+
+/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
+ call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
+ getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
+ lastIndex, length, parse, prototype, push, replace, slice, stringify,
+ test, toJSON, toString, valueOf
+*/
+
+
+// Create a JSON object only if one does not already exist. We create the
+// methods in a closure to avoid creating global variables.