backaid 0.1.9 → 0.2.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/.rspec +2 -0
- data/README.md +1 -1
- data/backaid.gemspec +7 -3
- data/lib/generators/backaid/backaid_generator.rb +36 -23
- data/spec/lib/generators/backaid_generator_spec.rb +6 -0
- data/spec/spec_helper.rb +17 -0
- data/vendor/assets/javascripts/backbone.js +1725 -2
- data/vendor/assets/javascripts/underscore.js +1489 -4
- metadata +67 -5
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 624e48d33889d50673a3c572830379eb6239851d
|
4
|
+
data.tar.gz: fd85f0552e5880673607d5a4a40c28629cb7aeaf
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 2afbf7bda39068b2b660de08459eec7813288032b538d403b9ed7be578ce183110d96b1452b09d273489f01324eb2f09bd02ec1f49973d22a7270e0bfd43f027
|
7
|
+
data.tar.gz: 7105669f6e6225a92b5ed293847808011d29fbd5e3ca31064e0c205b6a658e441bc8d2d4bcc6283b184f257fb693e6f4853107deb1229252e92298e147ab7073
|
data/.rspec
ADDED
data/README.md
CHANGED
data/backaid.gemspec
CHANGED
@@ -5,11 +5,11 @@ require 'backaid/version'
|
|
5
5
|
|
6
6
|
Gem::Specification.new do |spec|
|
7
7
|
spec.name = "backaid"
|
8
|
-
spec.version = "0.
|
8
|
+
spec.version = "0.2.0" #Backaid::VERSION
|
9
9
|
spec.authors = ["daviskoh"]
|
10
10
|
spec.email = ["koh.davis.0@gmail.com"]
|
11
|
-
spec.description = %q{Use
|
12
|
-
spec.summary = %q{Adds dependencies to asset
|
11
|
+
spec.description = %q{Use Backbone with Rails: Basic directory structure and dependencies installed.}
|
12
|
+
spec.summary = %q{Adds dependencies to asset pipeline. Use generator to setup backbone directory structure in rails app}
|
13
13
|
spec.homepage = "https://github.com/daviskoh/backaid"
|
14
14
|
spec.license = "MIT"
|
15
15
|
|
@@ -18,6 +18,10 @@ Gem::Specification.new do |spec|
|
|
18
18
|
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
|
19
19
|
spec.require_paths = ["lib", "vendor"]
|
20
20
|
|
21
|
+
spec.add_development_dependency "rails"
|
21
22
|
spec.add_development_dependency "bundler", "~> 1.3"
|
22
23
|
spec.add_development_dependency "rake"
|
24
|
+
spec.add_development_dependency "rspec", "~> 2.6"
|
25
|
+
spec.add_development_dependency "nyan-cat-formatter"
|
26
|
+
spec.add_development_dependency "generator_spec"
|
23
27
|
end
|
@@ -3,34 +3,47 @@ class BackaidGenerator < Rails::Generators::Base #NamedBase means name is requir
|
|
3
3
|
source_root File.expand_path('../templates', __FILE__)
|
4
4
|
|
5
5
|
# all public methods inside generator file execute when generator run
|
6
|
-
def gen_backbone_dir_structure
|
7
|
-
|
6
|
+
# def gen_backbone_dir_structure
|
7
|
+
# puts "Holla at your directories: models, collections, templates, views, routers"
|
8
8
|
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
9
|
+
# Dir.mkdir("app/assets/javascripts/backbone")
|
10
|
+
# ["models", "collections", "views", "routers", "templates"].each do |dir|
|
11
|
+
# Dir.mkdir("app/assets/javascripts/backbone/#{dir}")
|
12
|
+
# end
|
13
|
+
# end
|
14
|
+
|
15
|
+
%w{models collections views routers templates}.each do |dir|
|
16
|
+
empty_directory "app/assets/javascripts/backbone/#{dir}"
|
13
17
|
end
|
14
18
|
|
15
|
-
def require_backbone
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
+
# def require_backbone
|
20
|
+
# append_specific 'app/assets/javascripts/application.js' do |line|
|
21
|
+
# line = line == "//= require_tree .\n" ? "//= require underscore\n//= require backbone\n//= require_tree ./backbone/models\n//= require_tree ./backbone/collections\n//= require_tree ./backbone/templates\n//= require_tree ./backbone/views\n//= require_tree ./backbone/routers" : line
|
22
|
+
# end
|
19
23
|
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
end
|
24
|
+
# append_specific 'app/views/layouts/application.html.erb' do |line|
|
25
|
+
# line = line == "<%= yield %>\n" ? line + "\n<%= javascript_include_tag 'application' %>" : line
|
26
|
+
# end
|
27
|
+
# end
|
24
28
|
|
25
|
-
|
29
|
+
# require depedencies in manifest file
|
30
|
+
insert_into_file 'app/assets/javascripts/application.js', "//= require underscore\n//= require backbone\n//= require_tree ./backbone/models\n//= require_tree ./backbone/collections\n//= require_tree ./backbone/templates\n//= require_tree ./backbone/views\n//= require_tree ./backbone/routers", :after => "//= require_tree .\n"
|
31
|
+
# require in html file
|
32
|
+
insert_into_file 'app/views/layouts/application.html.erb', "\n<%= javascript_include_tag 'application' %>", :after => "<%= yield %>\n"
|
33
|
+
# remove extra include incude tag in layout html
|
34
|
+
insert_into_file 'app/views/layouts/application.html.erb', "", :after => "<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>"
|
26
35
|
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
end
|
36
|
+
|
37
|
+
puts "Holla at your directories: models, collections, templates, views, routers"
|
38
|
+
# private
|
31
39
|
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
end
|
40
|
+
# def append_specific(path)
|
41
|
+
# lines = IO.readlines(path).map do |line|
|
42
|
+
# yield line
|
43
|
+
# end
|
44
|
+
|
45
|
+
# File.open(path, 'w') do |file|
|
46
|
+
# file.puts lines
|
47
|
+
# end
|
48
|
+
# end
|
36
49
|
end
|
data/spec/spec_helper.rb
ADDED
@@ -0,0 +1,17 @@
|
|
1
|
+
# This file was generated by the `rspec --init` command. Conventionally, all
|
2
|
+
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
|
3
|
+
# Require this file using `require "spec_helper"` to ensure that it is only
|
4
|
+
# loaded once.
|
5
|
+
#
|
6
|
+
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
|
7
|
+
RSpec.configure do |config|
|
8
|
+
config.treat_symbols_as_metadata_keys_with_true_values = true
|
9
|
+
config.run_all_when_everything_filtered = true
|
10
|
+
config.filter_run :focus
|
11
|
+
|
12
|
+
# Run specs in random order to surface order dependencies. If you find an
|
13
|
+
# order dependency and want to debug it, you can fix the order by providing
|
14
|
+
# the seed, which is printed after each run.
|
15
|
+
# --seed 1234
|
16
|
+
config.order = 'random'
|
17
|
+
end
|
@@ -1,2 +1,1725 @@
|
|
1
|
-
(function(){var t=this;var e=t.Backbone;var i=[];var r=i.push;var s=i.slice;var n=i.splice;var a;if(typeof exports!=="undefined"){a=exports}else{a=t.Backbone={}}a.VERSION="1.1.0";var h=t._;if(!h&&typeof require!=="undefined")h=require("underscore");a.$=t.jQuery||t.Zepto||t.ender||t.$;a.noConflict=function(){t.Backbone=e;return this};a.emulateHTTP=false;a.emulateJSON=false;var o=a.Events={on:function(t,e,i){if(!l(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var r=this._events[t]||(this._events[t]=[]);r.push({callback:e,context:i,ctx:i||this});return this},once:function(t,e,i){if(!l(this,"once",t,[e,i])||!e)return this;var r=this;var s=h.once(function(){r.off(t,s);e.apply(this,arguments)});s._callback=e;return this.on(t,s,i)},off:function(t,e,i){var r,s,n,a,o,u,c,f;if(!this._events||!l(this,"off",t,[e,i]))return this;if(!t&&!e&&!i){this._events={};return this}a=t?[t]:h.keys(this._events);for(o=0,u=a.length;o<u;o++){t=a[o];if(n=this._events[t]){this._events[t]=r=[];if(e||i){for(c=0,f=n.length;c<f;c++){s=n[c];if(e&&e!==s.callback&&e!==s.callback._callback||i&&i!==s.context){r.push(s)}}}if(!r.length)delete this._events[t]}}return this},trigger:function(t){if(!this._events)return this;var e=s.call(arguments,1);if(!l(this,"trigger",t,e))return this;var i=this._events[t];var r=this._events.all;if(i)c(i,e);if(r)c(r,arguments);return this},stopListening:function(t,e,i){var r=this._listeningTo;if(!r)return this;var s=!e&&!i;if(!i&&typeof e==="object")i=this;if(t)(r={})[t._listenId]=t;for(var n in r){t=r[n];t.off(e,i,this);if(s||h.isEmpty(t._events))delete this._listeningTo[n]}return this}};var u=/\s+/;var l=function(t,e,i,r){if(!i)return true;if(typeof i==="object"){for(var s in i){t[e].apply(t,[s,i[s]].concat(r))}return false}if(u.test(i)){var n=i.split(u);for(var a=0,h=n.length;a<h;a++){t[e].apply(t,[n[a]].concat(r))}return false}return true};var c=function(t,e){var i,r=-1,s=t.length,n=e[0],a=e[1],h=e[2];switch(e.length){case 0:while(++r<s)(i=t[r]).callback.call(i.ctx);return;case 1:while(++r<s)(i=t[r]).callback.call(i.ctx,n);return;case 2:while(++r<s)(i=t[r]).callback.call(i.ctx,n,a);return;case 3:while(++r<s)(i=t[r]).callback.call(i.ctx,n,a,h);return;default:while(++r<s)(i=t[r]).callback.apply(i.ctx,e)}};var f={listenTo:"on",listenToOnce:"once"};h.each(f,function(t,e){o[e]=function(e,i,r){var s=this._listeningTo||(this._listeningTo={});var n=e._listenId||(e._listenId=h.uniqueId("l"));s[n]=e;if(!r&&typeof i==="object")r=this;e[t](i,r,this);return this}});o.bind=o.on;o.unbind=o.off;h.extend(a,o);var d=a.Model=function(t,e){var i=t||{};e||(e={});this.cid=h.uniqueId("c");this.attributes={};if(e.collection)this.collection=e.collection;if(e.parse)i=this.parse(i,e)||{};i=h.defaults({},i,h.result(this,"defaults"));this.set(i,e);this.changed={};this.initialize.apply(this,arguments)};h.extend(d.prototype,o,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(t){return h.clone(this.attributes)},sync:function(){return a.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return h.escape(this.get(t))},has:function(t){return this.get(t)!=null},set:function(t,e,i){var r,s,n,a,o,u,l,c;if(t==null)return this;if(typeof t==="object"){s=t;i=e}else{(s={})[t]=e}i||(i={});if(!this._validate(s,i))return false;n=i.unset;o=i.silent;a=[];u=this._changing;this._changing=true;if(!u){this._previousAttributes=h.clone(this.attributes);this.changed={}}c=this.attributes,l=this._previousAttributes;if(this.idAttribute in s)this.id=s[this.idAttribute];for(r in s){e=s[r];if(!h.isEqual(c[r],e))a.push(r);if(!h.isEqual(l[r],e)){this.changed[r]=e}else{delete this.changed[r]}n?delete c[r]:c[r]=e}if(!o){if(a.length)this._pending=true;for(var f=0,d=a.length;f<d;f++){this.trigger("change:"+a[f],this,c[a[f]],i)}}if(u)return this;if(!o){while(this._pending){this._pending=false;this.trigger("change",this,i)}}this._pending=false;this._changing=false;return this},unset:function(t,e){return this.set(t,void 0,h.extend({},e,{unset:true}))},clear:function(t){var e={};for(var i in this.attributes)e[i]=void 0;return this.set(e,h.extend({},t,{unset:true}))},hasChanged:function(t){if(t==null)return!h.isEmpty(this.changed);return h.has(this.changed,t)},changedAttributes:function(t){if(!t)return this.hasChanged()?h.clone(this.changed):false;var e,i=false;var r=this._changing?this._previousAttributes:this.attributes;for(var s in t){if(h.isEqual(r[s],e=t[s]))continue;(i||(i={}))[s]=e}return i},previous:function(t){if(t==null||!this._previousAttributes)return null;return this._previousAttributes[t]},previousAttributes:function(){return h.clone(this._previousAttributes)},fetch:function(t){t=t?h.clone(t):{};if(t.parse===void 0)t.parse=true;var e=this;var i=t.success;t.success=function(r){if(!e.set(e.parse(r,t),t))return false;if(i)i(e,r,t);e.trigger("sync",e,r,t)};M(this,t);return this.sync("read",this,t)},save:function(t,e,i){var r,s,n,a=this.attributes;if(t==null||typeof t==="object"){r=t;i=e}else{(r={})[t]=e}i=h.extend({validate:true},i);if(r&&!i.wait){if(!this.set(r,i))return false}else{if(!this._validate(r,i))return false}if(r&&i.wait){this.attributes=h.extend({},a,r)}if(i.parse===void 0)i.parse=true;var o=this;var u=i.success;i.success=function(t){o.attributes=a;var e=o.parse(t,i);if(i.wait)e=h.extend(r||{},e);if(h.isObject(e)&&!o.set(e,i)){return false}if(u)u(o,t,i);o.trigger("sync",o,t,i)};M(this,i);s=this.isNew()?"create":i.patch?"patch":"update";if(s==="patch")i.attrs=r;n=this.sync(s,this,i);if(r&&i.wait)this.attributes=a;return n},destroy:function(t){t=t?h.clone(t):{};var e=this;var i=t.success;var r=function(){e.trigger("destroy",e,e.collection,t)};t.success=function(s){if(t.wait||e.isNew())r();if(i)i(e,s,t);if(!e.isNew())e.trigger("sync",e,s,t)};if(this.isNew()){t.success();return false}M(this,t);var s=this.sync("delete",this,t);if(!t.wait)r();return s},url:function(){var t=h.result(this,"urlRoot")||h.result(this.collection,"url")||U();if(this.isNew())return t;return t+(t.charAt(t.length-1)==="/"?"":"/")+encodeURIComponent(this.id)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return this.id==null},isValid:function(t){return this._validate({},h.extend(t||{},{validate:true}))},_validate:function(t,e){if(!e.validate||!this.validate)return true;t=h.extend({},this.attributes,t);var i=this.validationError=this.validate(t,e)||null;if(!i)return true;this.trigger("invalid",this,i,h.extend(e,{validationError:i}));return false}});var p=["keys","values","pairs","invert","pick","omit"];h.each(p,function(t){d.prototype[t]=function(){var e=s.call(arguments);e.unshift(this.attributes);return h[t].apply(h,e)}});var v=a.Collection=function(t,e){e||(e={});if(e.model)this.model=e.model;if(e.comparator!==void 0)this.comparator=e.comparator;this._reset();this.initialize.apply(this,arguments);if(t)this.reset(t,h.extend({silent:true},e))};var g={add:true,remove:true,merge:true};var m={add:true,remove:false};h.extend(v.prototype,o,{model:d,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return a.sync.apply(this,arguments)},add:function(t,e){return this.set(t,h.extend({merge:false},e,m))},remove:function(t,e){var i=!h.isArray(t);t=i?[t]:h.clone(t);e||(e={});var r,s,n,a;for(r=0,s=t.length;r<s;r++){a=t[r]=this.get(t[r]);if(!a)continue;delete this._byId[a.id];delete this._byId[a.cid];n=this.indexOf(a);this.models.splice(n,1);this.length--;if(!e.silent){e.index=n;a.trigger("remove",a,this,e)}this._removeReference(a)}return i?t[0]:t},set:function(t,e){e=h.defaults({},e,g);if(e.parse)t=this.parse(t,e);var i=!h.isArray(t);t=i?t?[t]:[]:h.clone(t);var r,s,n,a,o,u,l;var c=e.at;var f=this.model;var p=this.comparator&&c==null&&e.sort!==false;var v=h.isString(this.comparator)?this.comparator:null;var m=[],y=[],_={};var w=e.add,b=e.merge,x=e.remove;var E=!p&&w&&x?[]:false;for(r=0,s=t.length;r<s;r++){o=t[r];if(o instanceof d){n=a=o}else{n=o[f.prototype.idAttribute]}if(u=this.get(n)){if(x)_[u.cid]=true;if(b){o=o===a?a.attributes:o;if(e.parse)o=u.parse(o,e);u.set(o,e);if(p&&!l&&u.hasChanged(v))l=true}t[r]=u}else if(w){a=t[r]=this._prepareModel(o,e);if(!a)continue;m.push(a);a.on("all",this._onModelEvent,this);this._byId[a.cid]=a;if(a.id!=null)this._byId[a.id]=a}if(E)E.push(u||a)}if(x){for(r=0,s=this.length;r<s;++r){if(!_[(a=this.models[r]).cid])y.push(a)}if(y.length)this.remove(y,e)}if(m.length||E&&E.length){if(p)l=true;this.length+=m.length;if(c!=null){for(r=0,s=m.length;r<s;r++){this.models.splice(c+r,0,m[r])}}else{if(E)this.models.length=0;var T=E||m;for(r=0,s=T.length;r<s;r++){this.models.push(T[r])}}}if(l)this.sort({silent:true});if(!e.silent){for(r=0,s=m.length;r<s;r++){(a=m[r]).trigger("add",a,this,e)}if(l||E&&E.length)this.trigger("sort",this,e)}return i?t[0]:t},reset:function(t,e){e||(e={});for(var i=0,r=this.models.length;i<r;i++){this._removeReference(this.models[i])}e.previousModels=this.models;this._reset();t=this.add(t,h.extend({silent:true},e));if(!e.silent)this.trigger("reset",this,e);return t},push:function(t,e){return this.add(t,h.extend({at:this.length},e))},pop:function(t){var e=this.at(this.length-1);this.remove(e,t);return e},unshift:function(t,e){return this.add(t,h.extend({at:0},e))},shift:function(t){var e=this.at(0);this.remove(e,t);return e},slice:function(){return s.apply(this.models,arguments)},get:function(t){if(t==null)return void 0;return this._byId[t.id]||this._byId[t.cid]||this._byId[t]},at:function(t){return this.models[t]},where:function(t,e){if(h.isEmpty(t))return e?void 0:[];return this[e?"find":"filter"](function(e){for(var i in t){if(t[i]!==e.get(i))return false}return true})},findWhere:function(t){return this.where(t,true)},sort:function(t){if(!this.comparator)throw new Error("Cannot sort a set without a comparator");t||(t={});if(h.isString(this.comparator)||this.comparator.length===1){this.models=this.sortBy(this.comparator,this)}else{this.models.sort(h.bind(this.comparator,this))}if(!t.silent)this.trigger("sort",this,t);return this},pluck:function(t){return h.invoke(this.models,"get",t)},fetch:function(t){t=t?h.clone(t):{};if(t.parse===void 0)t.parse=true;var e=t.success;var i=this;t.success=function(r){var s=t.reset?"reset":"set";i[s](r,t);if(e)e(i,r,t);i.trigger("sync",i,r,t)};M(this,t);return this.sync("read",this,t)},create:function(t,e){e=e?h.clone(e):{};if(!(t=this._prepareModel(t,e)))return false;if(!e.wait)this.add(t,e);var i=this;var r=e.success;e.success=function(t,e,s){if(s.wait)i.add(t,s);if(r)r(t,e,s)};t.save(null,e);return t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0;this.models=[];this._byId={}},_prepareModel:function(t,e){if(t instanceof d){if(!t.collection)t.collection=this;return t}e=e?h.clone(e):{};e.collection=this;var i=new this.model(t,e);if(!i.validationError)return i;this.trigger("invalid",this,i.validationError,e);return false},_removeReference:function(t){if(this===t.collection)delete t.collection;t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,r){if((t==="add"||t==="remove")&&i!==this)return;if(t==="destroy")this.remove(e,r);if(e&&t==="change:"+e.idAttribute){delete this._byId[e.previous(e.idAttribute)];if(e.id!=null)this._byId[e.id]=e}this.trigger.apply(this,arguments)}});var y=["forEach","each","map","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","max","min","toArray","size","first","head","take","initial","rest","tail","drop","last","without","difference","indexOf","shuffle","lastIndexOf","isEmpty","chain"];h.each(y,function(t){v.prototype[t]=function(){var e=s.call(arguments);e.unshift(this.models);return h[t].apply(h,e)}});var _=["groupBy","countBy","sortBy"];h.each(_,function(t){v.prototype[t]=function(e,i){var r=h.isFunction(e)?e:function(t){return t.get(e)};return h[t](this.models,r,i)}});var w=a.View=function(t){this.cid=h.uniqueId("view");t||(t={});h.extend(this,h.pick(t,x));this._ensureElement();this.initialize.apply(this,arguments);this.delegateEvents()};var b=/^(\S+)\s*(.*)$/;var x=["model","collection","el","id","attributes","className","tagName","events"];h.extend(w.prototype,o,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){this.$el.remove();this.stopListening();return this},setElement:function(t,e){if(this.$el)this.undelegateEvents();this.$el=t instanceof a.$?t:a.$(t);this.el=this.$el[0];if(e!==false)this.delegateEvents();return this},delegateEvents:function(t){if(!(t||(t=h.result(this,"events"))))return this;this.undelegateEvents();for(var e in t){var i=t[e];if(!h.isFunction(i))i=this[t[e]];if(!i)continue;var r=e.match(b);var s=r[1],n=r[2];i=h.bind(i,this);s+=".delegateEvents"+this.cid;if(n===""){this.$el.on(s,i)}else{this.$el.on(s,n,i)}}return this},undelegateEvents:function(){this.$el.off(".delegateEvents"+this.cid);return this},_ensureElement:function(){if(!this.el){var t=h.extend({},h.result(this,"attributes"));if(this.id)t.id=h.result(this,"id");if(this.className)t["class"]=h.result(this,"className");var e=a.$("<"+h.result(this,"tagName")+">").attr(t);this.setElement(e,false)}else{this.setElement(h.result(this,"el"),false)}}});a.sync=function(t,e,i){var r=T[t];h.defaults(i||(i={}),{emulateHTTP:a.emulateHTTP,emulateJSON:a.emulateJSON});var s={type:r,dataType:"json"};if(!i.url){s.url=h.result(e,"url")||U()}if(i.data==null&&e&&(t==="create"||t==="update"||t==="patch")){s.contentType="application/json";s.data=JSON.stringify(i.attrs||e.toJSON(i))}if(i.emulateJSON){s.contentType="application/x-www-form-urlencoded";s.data=s.data?{model:s.data}:{}}if(i.emulateHTTP&&(r==="PUT"||r==="DELETE"||r==="PATCH")){s.type="POST";if(i.emulateJSON)s.data._method=r;var n=i.beforeSend;i.beforeSend=function(t){t.setRequestHeader("X-HTTP-Method-Override",r);if(n)return n.apply(this,arguments)}}if(s.type!=="GET"&&!i.emulateJSON){s.processData=false}if(s.type==="PATCH"&&E){s.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")}}var o=i.xhr=a.ajax(h.extend(s,i));e.trigger("request",e,o,i);return o};var E=typeof window!=="undefined"&&!!window.ActiveXObject&&!(window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent);var T={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};a.ajax=function(){return a.$.ajax.apply(a.$,arguments)};var k=a.Router=function(t){t||(t={});if(t.routes)this.routes=t.routes;this._bindRoutes();this.initialize.apply(this,arguments)};var S=/\((.*?)\)/g;var $=/(\(\?)?:\w+/g;var H=/\*\w+/g;var A=/[\-{}\[\]+?.,\\\^$|#\s]/g;h.extend(k.prototype,o,{initialize:function(){},route:function(t,e,i){if(!h.isRegExp(t))t=this._routeToRegExp(t);if(h.isFunction(e)){i=e;e=""}if(!i)i=this[e];var r=this;a.history.route(t,function(s){var n=r._extractParameters(t,s);i&&i.apply(r,n);r.trigger.apply(r,["route:"+e].concat(n));r.trigger("route",e,n);a.history.trigger("route",r,e,n)});return this},navigate:function(t,e){a.history.navigate(t,e);return this},_bindRoutes:function(){if(!this.routes)return;this.routes=h.result(this,"routes");var t,e=h.keys(this.routes);while((t=e.pop())!=null){this.route(t,this.routes[t])}},_routeToRegExp:function(t){t=t.replace(A,"\\$&").replace(S,"(?:$1)?").replace($,function(t,e){return e?t:"([^/]+)"}).replace(H,"(.*?)");return new RegExp("^"+t+"$")},_extractParameters:function(t,e){var i=t.exec(e).slice(1);return h.map(i,function(t){return t?decodeURIComponent(t):null})}});var I=a.History=function(){this.handlers=[];h.bindAll(this,"checkUrl");if(typeof window!=="undefined"){this.location=window.location;this.history=window.history}};var N=/^[#\/]|\s+$/g;var O=/^\/+|\/+$/g;var P=/msie [\w.]+/;var C=/\/$/;var j=/[?#].*$/;I.started=false;h.extend(I.prototype,o,{interval:50,getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(t==null){if(this._hasPushState||!this._wantsHashChange||e){t=this.location.pathname;var i=this.root.replace(C,"");if(!t.indexOf(i))t=t.slice(i.length)}else{t=this.getHash()}}return t.replace(N,"")},start:function(t){if(I.started)throw new Error("Backbone.history has already been started");I.started=true;this.options=h.extend({root:"/"},this.options,t);this.root=this.options.root;this._wantsHashChange=this.options.hashChange!==false;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var e=this.getFragment();var i=document.documentMode;var r=P.exec(navigator.userAgent.toLowerCase())&&(!i||i<=7);this.root=("/"+this.root+"/").replace(O,"/");if(r&&this._wantsHashChange){this.iframe=a.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo("body")[0].contentWindow;this.navigate(e)}if(this._hasPushState){a.$(window).on("popstate",this.checkUrl)}else if(this._wantsHashChange&&"onhashchange"in window&&!r){a.$(window).on("hashchange",this.checkUrl)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}this.fragment=e;var s=this.location;var n=s.pathname.replace(/[^\/]$/,"$&/")===this.root;if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!n){this.fragment=this.getFragment(null,true);this.location.replace(this.root+this.location.search+"#"+this.fragment);return true}else if(this._hasPushState&&n&&s.hash){this.fragment=this.getHash().replace(N,"");this.history.replaceState({},document.title,this.root+this.fragment+s.search)}}if(!this.options.silent)return this.loadUrl()},stop:function(){a.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl);clearInterval(this._checkUrlInterval);I.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getFragment(this.getHash(this.iframe))}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){t=this.fragment=this.getFragment(t);return h.any(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!I.started)return false;if(!e||e===true)e={trigger:!!e};var i=this.root+(t=this.getFragment(t||""));t=t.replace(j,"");if(this.fragment===t)return;this.fragment=t;if(t===""&&i!=="/")i=i.slice(0,-1);if(this._hasPushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,i)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getFragment(this.getHash(this.iframe))){if(!e.replace)this.iframe.document.open().close();this._updateHash(this.iframe.location,t,e.replace)}}else{return this.location.assign(i)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});a.history=new I;var R=function(t,e){var i=this;var r;if(t&&h.has(t,"constructor")){r=t.constructor}else{r=function(){return i.apply(this,arguments)}}h.extend(r,i,e);var s=function(){this.constructor=r};s.prototype=i.prototype;r.prototype=new s;if(t)h.extend(r.prototype,t);r.__super__=i.prototype;return r};d.extend=v.extend=k.extend=w.extend=I.extend=R;var U=function(){throw new Error('A "url" property or function must be specified')};var M=function(t,e){var i=e.error;e.error=function(r){if(i)i(t,r,e);t.trigger("error",t,r,e)}}}).call(this);
|
2
|
-
|
1
|
+
// Backbone.js 1.1.2
|
2
|
+
|
3
|
+
// (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
4
|
+
// Backbone may be freely distributed under the MIT license.
|
5
|
+
// For all details and documentation:
|
6
|
+
// http://backbonejs.org
|
7
|
+
|
8
|
+
(function(root, factory) {
|
9
|
+
|
10
|
+
// Set up Backbone appropriately for the environment. Start with AMD.
|
11
|
+
if (typeof define === 'function' && define.amd) {
|
12
|
+
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
|
13
|
+
// Export global even in AMD case in case this script is loaded with
|
14
|
+
// others that may still expect a global Backbone.
|
15
|
+
root.Backbone = factory(root, exports, _, $);
|
16
|
+
});
|
17
|
+
|
18
|
+
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
|
19
|
+
} else if (typeof exports !== 'undefined') {
|
20
|
+
var _ = require('underscore');
|
21
|
+
factory(root, exports, _);
|
22
|
+
|
23
|
+
// Finally, as a browser global.
|
24
|
+
} else {
|
25
|
+
root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
|
26
|
+
}
|
27
|
+
|
28
|
+
}(this, function(root, Backbone, _, $) {
|
29
|
+
|
30
|
+
// Initial Setup
|
31
|
+
// -------------
|
32
|
+
|
33
|
+
// Save the previous value of the `Backbone` variable, so that it can be
|
34
|
+
// restored later on, if `noConflict` is used.
|
35
|
+
var previousBackbone = root.Backbone;
|
36
|
+
|
37
|
+
// Create local references to array methods we'll want to use later.
|
38
|
+
var array = [];
|
39
|
+
var slice = array.slice;
|
40
|
+
|
41
|
+
// Current version of the library. Keep in sync with `package.json`.
|
42
|
+
Backbone.VERSION = '1.1.2';
|
43
|
+
|
44
|
+
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
|
45
|
+
// the `$` variable.
|
46
|
+
Backbone.$ = $;
|
47
|
+
|
48
|
+
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
|
49
|
+
// to its previous owner. Returns a reference to this Backbone object.
|
50
|
+
Backbone.noConflict = function() {
|
51
|
+
root.Backbone = previousBackbone;
|
52
|
+
return this;
|
53
|
+
};
|
54
|
+
|
55
|
+
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
|
56
|
+
// will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
|
57
|
+
// set a `X-Http-Method-Override` header.
|
58
|
+
Backbone.emulateHTTP = false;
|
59
|
+
|
60
|
+
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
|
61
|
+
// `application/json` requests ... this will encode the body as
|
62
|
+
// `application/x-www-form-urlencoded` instead and will send the model in a
|
63
|
+
// form param named `model`.
|
64
|
+
Backbone.emulateJSON = false;
|
65
|
+
|
66
|
+
// Backbone.Events
|
67
|
+
// ---------------
|
68
|
+
|
69
|
+
// A module that can be mixed in to *any object* in order to provide it with
|
70
|
+
// custom events. You may bind with `on` or remove with `off` callback
|
71
|
+
// functions to an event; `trigger`-ing an event fires all callbacks in
|
72
|
+
// succession.
|
73
|
+
//
|
74
|
+
// var object = {};
|
75
|
+
// _.extend(object, Backbone.Events);
|
76
|
+
// object.on('expand', function(){ alert('expanded'); });
|
77
|
+
// object.trigger('expand');
|
78
|
+
//
|
79
|
+
var Events = Backbone.Events = {
|
80
|
+
|
81
|
+
// Bind an event to a `callback` function. Passing `"all"` will bind
|
82
|
+
// the callback to all events fired.
|
83
|
+
on: function(name, callback, context) {
|
84
|
+
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
|
85
|
+
this._events || (this._events = {});
|
86
|
+
var events = this._events[name] || (this._events[name] = []);
|
87
|
+
events.push({callback: callback, context: context, ctx: context || this});
|
88
|
+
return this;
|
89
|
+
},
|
90
|
+
|
91
|
+
// Bind an event to only be triggered a single time. After the first time
|
92
|
+
// the callback is invoked, it will be removed.
|
93
|
+
once: function(name, callback, context) {
|
94
|
+
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
|
95
|
+
var self = this;
|
96
|
+
var once = _.once(function() {
|
97
|
+
self.off(name, once);
|
98
|
+
callback.apply(this, arguments);
|
99
|
+
});
|
100
|
+
once._callback = callback;
|
101
|
+
return this.on(name, once, context);
|
102
|
+
},
|
103
|
+
|
104
|
+
// Remove one or many callbacks. If `context` is null, removes all
|
105
|
+
// callbacks with that function. If `callback` is null, removes all
|
106
|
+
// callbacks for the event. If `name` is null, removes all bound
|
107
|
+
// callbacks for all events.
|
108
|
+
off: function(name, callback, context) {
|
109
|
+
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
|
110
|
+
|
111
|
+
// Remove all callbacks for all events.
|
112
|
+
if (!name && !callback && !context) {
|
113
|
+
this._events = void 0;
|
114
|
+
return this;
|
115
|
+
}
|
116
|
+
|
117
|
+
var names = name ? [name] : _.keys(this._events);
|
118
|
+
for (var i = 0, length = names.length; i < length; i++) {
|
119
|
+
name = names[i];
|
120
|
+
|
121
|
+
// Bail out if there are no events stored.
|
122
|
+
var events = this._events[name];
|
123
|
+
if (!events) continue;
|
124
|
+
|
125
|
+
// Remove all callbacks for this event.
|
126
|
+
if (!callback && !context) {
|
127
|
+
delete this._events[name];
|
128
|
+
continue;
|
129
|
+
}
|
130
|
+
|
131
|
+
// Find any remaining events.
|
132
|
+
var remaining = [];
|
133
|
+
for (var j = 0, k = events.length; j < k; j++) {
|
134
|
+
var event = events[j];
|
135
|
+
if (
|
136
|
+
callback && callback !== event.callback &&
|
137
|
+
callback !== event.callback._callback ||
|
138
|
+
context && context !== event.context
|
139
|
+
) {
|
140
|
+
remaining.push(event);
|
141
|
+
}
|
142
|
+
}
|
143
|
+
|
144
|
+
// Replace events if there are any remaining. Otherwise, clean up.
|
145
|
+
if (remaining.length) {
|
146
|
+
this._events[name] = remaining;
|
147
|
+
} else {
|
148
|
+
delete this._events[name];
|
149
|
+
}
|
150
|
+
}
|
151
|
+
|
152
|
+
return this;
|
153
|
+
},
|
154
|
+
|
155
|
+
// Trigger one or many events, firing all bound callbacks. Callbacks are
|
156
|
+
// passed the same arguments as `trigger` is, apart from the event name
|
157
|
+
// (unless you're listening on `"all"`, which will cause your callback to
|
158
|
+
// receive the true name of the event as the first argument).
|
159
|
+
trigger: function(name) {
|
160
|
+
if (!this._events) return this;
|
161
|
+
var args = slice.call(arguments, 1);
|
162
|
+
if (!eventsApi(this, 'trigger', name, args)) return this;
|
163
|
+
var events = this._events[name];
|
164
|
+
var allEvents = this._events.all;
|
165
|
+
if (events) triggerEvents(events, args);
|
166
|
+
if (allEvents) triggerEvents(allEvents, arguments);
|
167
|
+
return this;
|
168
|
+
},
|
169
|
+
|
170
|
+
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
|
171
|
+
// listen to an event in another object ... keeping track of what it's
|
172
|
+
// listening to.
|
173
|
+
listenTo: function(obj, name, callback) {
|
174
|
+
var listeningTo = this._listeningTo || (this._listeningTo = {});
|
175
|
+
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
|
176
|
+
listeningTo[id] = obj;
|
177
|
+
if (!callback && typeof name === 'object') callback = this;
|
178
|
+
obj.on(name, callback, this);
|
179
|
+
return this;
|
180
|
+
},
|
181
|
+
|
182
|
+
listenToOnce: function(obj, name, callback) {
|
183
|
+
if (typeof name === 'object') {
|
184
|
+
for (var event in name) this.listenToOnce(obj, event, name[event]);
|
185
|
+
return this;
|
186
|
+
}
|
187
|
+
var cb = _.once(function() {
|
188
|
+
this.stopListening(obj, name, cb);
|
189
|
+
callback.apply(this, arguments);
|
190
|
+
});
|
191
|
+
cb._callback = callback;
|
192
|
+
return this.listenTo(obj, name, cb);
|
193
|
+
},
|
194
|
+
|
195
|
+
// Tell this object to stop listening to either specific events ... or
|
196
|
+
// to every object it's currently listening to.
|
197
|
+
stopListening: function(obj, name, callback) {
|
198
|
+
var listeningTo = this._listeningTo;
|
199
|
+
if (!listeningTo) return this;
|
200
|
+
var remove = !name && !callback;
|
201
|
+
if (!callback && typeof name === 'object') callback = this;
|
202
|
+
if (obj) (listeningTo = {})[obj._listenId] = obj;
|
203
|
+
for (var id in listeningTo) {
|
204
|
+
obj = listeningTo[id];
|
205
|
+
obj.off(name, callback, this);
|
206
|
+
if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
|
207
|
+
}
|
208
|
+
return this;
|
209
|
+
}
|
210
|
+
|
211
|
+
};
|
212
|
+
|
213
|
+
// Regular expression used to split event strings.
|
214
|
+
var eventSplitter = /\s+/;
|
215
|
+
|
216
|
+
// Implement fancy features of the Events API such as multiple event
|
217
|
+
// names `"change blur"` and jQuery-style event maps `{change: action}`
|
218
|
+
// in terms of the existing API.
|
219
|
+
var eventsApi = function(obj, action, name, rest) {
|
220
|
+
if (!name) return true;
|
221
|
+
|
222
|
+
// Handle event maps.
|
223
|
+
if (typeof name === 'object') {
|
224
|
+
for (var key in name) {
|
225
|
+
obj[action].apply(obj, [key, name[key]].concat(rest));
|
226
|
+
}
|
227
|
+
return false;
|
228
|
+
}
|
229
|
+
|
230
|
+
// Handle space separated event names.
|
231
|
+
if (eventSplitter.test(name)) {
|
232
|
+
var names = name.split(eventSplitter);
|
233
|
+
for (var i = 0, length = names.length; i < length; i++) {
|
234
|
+
obj[action].apply(obj, [names[i]].concat(rest));
|
235
|
+
}
|
236
|
+
return false;
|
237
|
+
}
|
238
|
+
|
239
|
+
return true;
|
240
|
+
};
|
241
|
+
|
242
|
+
// A difficult-to-believe, but optimized internal dispatch function for
|
243
|
+
// triggering events. Tries to keep the usual cases speedy (most internal
|
244
|
+
// Backbone events have 3 arguments).
|
245
|
+
var triggerEvents = function(events, args) {
|
246
|
+
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
|
247
|
+
switch (args.length) {
|
248
|
+
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
|
249
|
+
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
|
250
|
+
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
|
251
|
+
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
|
252
|
+
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
|
253
|
+
}
|
254
|
+
};
|
255
|
+
|
256
|
+
// Aliases for backwards compatibility.
|
257
|
+
Events.bind = Events.on;
|
258
|
+
Events.unbind = Events.off;
|
259
|
+
|
260
|
+
// Allow the `Backbone` object to serve as a global event bus, for folks who
|
261
|
+
// want global "pubsub" in a convenient place.
|
262
|
+
_.extend(Backbone, Events);
|
263
|
+
|
264
|
+
// Backbone.Model
|
265
|
+
// --------------
|
266
|
+
|
267
|
+
// Backbone **Models** are the basic data object in the framework --
|
268
|
+
// frequently representing a row in a table in a database on your server.
|
269
|
+
// A discrete chunk of data and a bunch of useful, related methods for
|
270
|
+
// performing computations and transformations on that data.
|
271
|
+
|
272
|
+
// Create a new model with the specified attributes. A client id (`cid`)
|
273
|
+
// is automatically generated and assigned for you.
|
274
|
+
var Model = Backbone.Model = function(attributes, options) {
|
275
|
+
var attrs = attributes || {};
|
276
|
+
options || (options = {});
|
277
|
+
this.cid = _.uniqueId('c');
|
278
|
+
this.attributes = {};
|
279
|
+
if (options.collection) this.collection = options.collection;
|
280
|
+
if (options.parse) attrs = this.parse(attrs, options) || {};
|
281
|
+
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
|
282
|
+
this.set(attrs, options);
|
283
|
+
this.changed = {};
|
284
|
+
this.initialize.apply(this, arguments);
|
285
|
+
};
|
286
|
+
|
287
|
+
// Attach all inheritable methods to the Model prototype.
|
288
|
+
_.extend(Model.prototype, Events, {
|
289
|
+
|
290
|
+
// A hash of attributes whose current and previous value differ.
|
291
|
+
changed: null,
|
292
|
+
|
293
|
+
// The value returned during the last failed validation.
|
294
|
+
validationError: null,
|
295
|
+
|
296
|
+
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
|
297
|
+
// CouchDB users may want to set this to `"_id"`.
|
298
|
+
idAttribute: 'id',
|
299
|
+
|
300
|
+
// Initialize is an empty function by default. Override it with your own
|
301
|
+
// initialization logic.
|
302
|
+
initialize: function(){},
|
303
|
+
|
304
|
+
// Return a copy of the model's `attributes` object.
|
305
|
+
toJSON: function(options) {
|
306
|
+
return _.clone(this.attributes);
|
307
|
+
},
|
308
|
+
|
309
|
+
// Proxy `Backbone.sync` by default -- but override this if you need
|
310
|
+
// custom syncing semantics for *this* particular model.
|
311
|
+
sync: function() {
|
312
|
+
return Backbone.sync.apply(this, arguments);
|
313
|
+
},
|
314
|
+
|
315
|
+
// Get the value of an attribute.
|
316
|
+
get: function(attr) {
|
317
|
+
return this.attributes[attr];
|
318
|
+
},
|
319
|
+
|
320
|
+
// Get the HTML-escaped value of an attribute.
|
321
|
+
escape: function(attr) {
|
322
|
+
return _.escape(this.get(attr));
|
323
|
+
},
|
324
|
+
|
325
|
+
// Returns `true` if the attribute contains a value that is not null
|
326
|
+
// or undefined.
|
327
|
+
has: function(attr) {
|
328
|
+
return this.get(attr) != null;
|
329
|
+
},
|
330
|
+
|
331
|
+
// Set a hash of model attributes on the object, firing `"change"`. This is
|
332
|
+
// the core primitive operation of a model, updating the data and notifying
|
333
|
+
// anyone who needs to know about the change in state. The heart of the beast.
|
334
|
+
set: function(key, val, options) {
|
335
|
+
var attr, attrs, unset, changes, silent, changing, prev, current;
|
336
|
+
if (key == null) return this;
|
337
|
+
|
338
|
+
// Handle both `"key", value` and `{key: value}` -style arguments.
|
339
|
+
if (typeof key === 'object') {
|
340
|
+
attrs = key;
|
341
|
+
options = val;
|
342
|
+
} else {
|
343
|
+
(attrs = {})[key] = val;
|
344
|
+
}
|
345
|
+
|
346
|
+
options || (options = {});
|
347
|
+
|
348
|
+
// Run validation.
|
349
|
+
if (!this._validate(attrs, options)) return false;
|
350
|
+
|
351
|
+
// Extract attributes and options.
|
352
|
+
unset = options.unset;
|
353
|
+
silent = options.silent;
|
354
|
+
changes = [];
|
355
|
+
changing = this._changing;
|
356
|
+
this._changing = true;
|
357
|
+
|
358
|
+
if (!changing) {
|
359
|
+
this._previousAttributes = _.clone(this.attributes);
|
360
|
+
this.changed = {};
|
361
|
+
}
|
362
|
+
current = this.attributes, prev = this._previousAttributes;
|
363
|
+
|
364
|
+
// Check for changes of `id`.
|
365
|
+
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
|
366
|
+
|
367
|
+
// For each `set` attribute, update or delete the current value.
|
368
|
+
for (attr in attrs) {
|
369
|
+
val = attrs[attr];
|
370
|
+
if (!_.isEqual(current[attr], val)) changes.push(attr);
|
371
|
+
if (!_.isEqual(prev[attr], val)) {
|
372
|
+
this.changed[attr] = val;
|
373
|
+
} else {
|
374
|
+
delete this.changed[attr];
|
375
|
+
}
|
376
|
+
unset ? delete current[attr] : current[attr] = val;
|
377
|
+
}
|
378
|
+
|
379
|
+
// Trigger all relevant attribute changes.
|
380
|
+
if (!silent) {
|
381
|
+
if (changes.length) this._pending = options;
|
382
|
+
for (var i = 0, length = changes.length; i < length; i++) {
|
383
|
+
this.trigger('change:' + changes[i], this, current[changes[i]], options);
|
384
|
+
}
|
385
|
+
}
|
386
|
+
|
387
|
+
// You might be wondering why there's a `while` loop here. Changes can
|
388
|
+
// be recursively nested within `"change"` events.
|
389
|
+
if (changing) return this;
|
390
|
+
if (!silent) {
|
391
|
+
while (this._pending) {
|
392
|
+
options = this._pending;
|
393
|
+
this._pending = false;
|
394
|
+
this.trigger('change', this, options);
|
395
|
+
}
|
396
|
+
}
|
397
|
+
this._pending = false;
|
398
|
+
this._changing = false;
|
399
|
+
return this;
|
400
|
+
},
|
401
|
+
|
402
|
+
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
|
403
|
+
// if the attribute doesn't exist.
|
404
|
+
unset: function(attr, options) {
|
405
|
+
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
|
406
|
+
},
|
407
|
+
|
408
|
+
// Clear all attributes on the model, firing `"change"`.
|
409
|
+
clear: function(options) {
|
410
|
+
var attrs = {};
|
411
|
+
for (var key in this.attributes) attrs[key] = void 0;
|
412
|
+
return this.set(attrs, _.extend({}, options, {unset: true}));
|
413
|
+
},
|
414
|
+
|
415
|
+
// Determine if the model has changed since the last `"change"` event.
|
416
|
+
// If you specify an attribute name, determine if that attribute has changed.
|
417
|
+
hasChanged: function(attr) {
|
418
|
+
if (attr == null) return !_.isEmpty(this.changed);
|
419
|
+
return _.has(this.changed, attr);
|
420
|
+
},
|
421
|
+
|
422
|
+
// Return an object containing all the attributes that have changed, or
|
423
|
+
// false if there are no changed attributes. Useful for determining what
|
424
|
+
// parts of a view need to be updated and/or what attributes need to be
|
425
|
+
// persisted to the server. Unset attributes will be set to undefined.
|
426
|
+
// You can also pass an attributes object to diff against the model,
|
427
|
+
// determining if there *would be* a change.
|
428
|
+
changedAttributes: function(diff) {
|
429
|
+
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
|
430
|
+
var val, changed = false;
|
431
|
+
var old = this._changing ? this._previousAttributes : this.attributes;
|
432
|
+
for (var attr in diff) {
|
433
|
+
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
|
434
|
+
(changed || (changed = {}))[attr] = val;
|
435
|
+
}
|
436
|
+
return changed;
|
437
|
+
},
|
438
|
+
|
439
|
+
// Get the previous value of an attribute, recorded at the time the last
|
440
|
+
// `"change"` event was fired.
|
441
|
+
previous: function(attr) {
|
442
|
+
if (attr == null || !this._previousAttributes) return null;
|
443
|
+
return this._previousAttributes[attr];
|
444
|
+
},
|
445
|
+
|
446
|
+
// Get all of the attributes of the model at the time of the previous
|
447
|
+
// `"change"` event.
|
448
|
+
previousAttributes: function() {
|
449
|
+
return _.clone(this._previousAttributes);
|
450
|
+
},
|
451
|
+
|
452
|
+
// Fetch the model from the server. If the server's representation of the
|
453
|
+
// model differs from its current attributes, they will be overridden,
|
454
|
+
// triggering a `"change"` event.
|
455
|
+
fetch: function(options) {
|
456
|
+
options = options ? _.clone(options) : {};
|
457
|
+
if (options.parse === void 0) options.parse = true;
|
458
|
+
var model = this;
|
459
|
+
var success = options.success;
|
460
|
+
options.success = function(resp) {
|
461
|
+
if (!model.set(model.parse(resp, options), options)) return false;
|
462
|
+
if (success) success(model, resp, options);
|
463
|
+
model.trigger('sync', model, resp, options);
|
464
|
+
};
|
465
|
+
wrapError(this, options);
|
466
|
+
return this.sync('read', this, options);
|
467
|
+
},
|
468
|
+
|
469
|
+
// Set a hash of model attributes, and sync the model to the server.
|
470
|
+
// If the server returns an attributes hash that differs, the model's
|
471
|
+
// state will be `set` again.
|
472
|
+
save: function(key, val, options) {
|
473
|
+
var attrs, method, xhr, attributes = this.attributes;
|
474
|
+
|
475
|
+
// Handle both `"key", value` and `{key: value}` -style arguments.
|
476
|
+
if (key == null || typeof key === 'object') {
|
477
|
+
attrs = key;
|
478
|
+
options = val;
|
479
|
+
} else {
|
480
|
+
(attrs = {})[key] = val;
|
481
|
+
}
|
482
|
+
|
483
|
+
options = _.extend({validate: true}, options);
|
484
|
+
|
485
|
+
// If we're not waiting and attributes exist, save acts as
|
486
|
+
// `set(attr).save(null, opts)` with validation. Otherwise, check if
|
487
|
+
// the model will be valid when the attributes, if any, are set.
|
488
|
+
if (attrs && !options.wait) {
|
489
|
+
if (!this.set(attrs, options)) return false;
|
490
|
+
} else {
|
491
|
+
if (!this._validate(attrs, options)) return false;
|
492
|
+
}
|
493
|
+
|
494
|
+
// Set temporary attributes if `{wait: true}`.
|
495
|
+
if (attrs && options.wait) {
|
496
|
+
this.attributes = _.extend({}, attributes, attrs);
|
497
|
+
}
|
498
|
+
|
499
|
+
// After a successful server-side save, the client is (optionally)
|
500
|
+
// updated with the server-side state.
|
501
|
+
if (options.parse === void 0) options.parse = true;
|
502
|
+
var model = this;
|
503
|
+
var success = options.success;
|
504
|
+
options.success = function(resp) {
|
505
|
+
// Ensure attributes are restored during synchronous saves.
|
506
|
+
model.attributes = attributes;
|
507
|
+
var serverAttrs = model.parse(resp, options);
|
508
|
+
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
|
509
|
+
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
|
510
|
+
return false;
|
511
|
+
}
|
512
|
+
if (success) success(model, resp, options);
|
513
|
+
model.trigger('sync', model, resp, options);
|
514
|
+
};
|
515
|
+
wrapError(this, options);
|
516
|
+
|
517
|
+
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
|
518
|
+
if (method === 'patch' && !options.attrs) options.attrs = attrs;
|
519
|
+
xhr = this.sync(method, this, options);
|
520
|
+
|
521
|
+
// Restore attributes.
|
522
|
+
if (attrs && options.wait) this.attributes = attributes;
|
523
|
+
|
524
|
+
return xhr;
|
525
|
+
},
|
526
|
+
|
527
|
+
// Destroy this model on the server if it was already persisted.
|
528
|
+
// Optimistically removes the model from its collection, if it has one.
|
529
|
+
// If `wait: true` is passed, waits for the server to respond before removal.
|
530
|
+
destroy: function(options) {
|
531
|
+
options = options ? _.clone(options) : {};
|
532
|
+
var model = this;
|
533
|
+
var success = options.success;
|
534
|
+
|
535
|
+
var destroy = function() {
|
536
|
+
model.stopListening();
|
537
|
+
model.trigger('destroy', model, model.collection, options);
|
538
|
+
};
|
539
|
+
|
540
|
+
options.success = function(resp) {
|
541
|
+
if (options.wait || model.isNew()) destroy();
|
542
|
+
if (success) success(model, resp, options);
|
543
|
+
if (!model.isNew()) model.trigger('sync', model, resp, options);
|
544
|
+
};
|
545
|
+
|
546
|
+
if (this.isNew()) {
|
547
|
+
options.success();
|
548
|
+
return false;
|
549
|
+
}
|
550
|
+
wrapError(this, options);
|
551
|
+
|
552
|
+
var xhr = this.sync('delete', this, options);
|
553
|
+
if (!options.wait) destroy();
|
554
|
+
return xhr;
|
555
|
+
},
|
556
|
+
|
557
|
+
// Default URL for the model's representation on the server -- if you're
|
558
|
+
// using Backbone's restful methods, override this to change the endpoint
|
559
|
+
// that will be called.
|
560
|
+
url: function() {
|
561
|
+
var base =
|
562
|
+
_.result(this, 'urlRoot') ||
|
563
|
+
_.result(this.collection, 'url') ||
|
564
|
+
urlError();
|
565
|
+
if (this.isNew()) return base;
|
566
|
+
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
|
567
|
+
},
|
568
|
+
|
569
|
+
// **parse** converts a response into the hash of attributes to be `set` on
|
570
|
+
// the model. The default implementation is just to pass the response along.
|
571
|
+
parse: function(resp, options) {
|
572
|
+
return resp;
|
573
|
+
},
|
574
|
+
|
575
|
+
// Create a new model with identical attributes to this one.
|
576
|
+
clone: function() {
|
577
|
+
return new this.constructor(this.attributes);
|
578
|
+
},
|
579
|
+
|
580
|
+
// A model is new if it has never been saved to the server, and lacks an id.
|
581
|
+
isNew: function() {
|
582
|
+
return !this.has(this.idAttribute);
|
583
|
+
},
|
584
|
+
|
585
|
+
// Check if the model is currently in a valid state.
|
586
|
+
isValid: function(options) {
|
587
|
+
return this._validate({}, _.extend(options || {}, { validate: true }));
|
588
|
+
},
|
589
|
+
|
590
|
+
// Run validation against the next complete set of model attributes,
|
591
|
+
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
|
592
|
+
_validate: function(attrs, options) {
|
593
|
+
if (!options.validate || !this.validate) return true;
|
594
|
+
attrs = _.extend({}, this.attributes, attrs);
|
595
|
+
var error = this.validationError = this.validate(attrs, options) || null;
|
596
|
+
if (!error) return true;
|
597
|
+
this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
|
598
|
+
return false;
|
599
|
+
}
|
600
|
+
|
601
|
+
});
|
602
|
+
|
603
|
+
// Underscore methods that we want to implement on the Model.
|
604
|
+
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit', 'chain', 'isEmpty'];
|
605
|
+
|
606
|
+
// Mix in each Underscore method as a proxy to `Model#attributes`.
|
607
|
+
_.each(modelMethods, function(method) {
|
608
|
+
if (!_[method]) return;
|
609
|
+
Model.prototype[method] = function() {
|
610
|
+
var args = slice.call(arguments);
|
611
|
+
args.unshift(this.attributes);
|
612
|
+
return _[method].apply(_, args);
|
613
|
+
};
|
614
|
+
});
|
615
|
+
|
616
|
+
// Backbone.Collection
|
617
|
+
// -------------------
|
618
|
+
|
619
|
+
// If models tend to represent a single row of data, a Backbone Collection is
|
620
|
+
// more analogous to a table full of data ... or a small slice or page of that
|
621
|
+
// table, or a collection of rows that belong together for a particular reason
|
622
|
+
// -- all of the messages in this particular folder, all of the documents
|
623
|
+
// belonging to this particular author, and so on. Collections maintain
|
624
|
+
// indexes of their models, both in order, and for lookup by `id`.
|
625
|
+
|
626
|
+
// Create a new **Collection**, perhaps to contain a specific type of `model`.
|
627
|
+
// If a `comparator` is specified, the Collection will maintain
|
628
|
+
// its models in sort order, as they're added and removed.
|
629
|
+
var Collection = Backbone.Collection = function(models, options) {
|
630
|
+
options || (options = {});
|
631
|
+
if (options.model) this.model = options.model;
|
632
|
+
if (options.comparator !== void 0) this.comparator = options.comparator;
|
633
|
+
this._reset();
|
634
|
+
this.initialize.apply(this, arguments);
|
635
|
+
if (models) this.reset(models, _.extend({silent: true}, options));
|
636
|
+
};
|
637
|
+
|
638
|
+
// Default options for `Collection#set`.
|
639
|
+
var setOptions = {add: true, remove: true, merge: true};
|
640
|
+
var addOptions = {add: true, remove: false};
|
641
|
+
|
642
|
+
// Define the Collection's inheritable methods.
|
643
|
+
_.extend(Collection.prototype, Events, {
|
644
|
+
|
645
|
+
// The default model for a collection is just a **Backbone.Model**.
|
646
|
+
// This should be overridden in most cases.
|
647
|
+
model: Model,
|
648
|
+
|
649
|
+
// Initialize is an empty function by default. Override it with your own
|
650
|
+
// initialization logic.
|
651
|
+
initialize: function(){},
|
652
|
+
|
653
|
+
// The JSON representation of a Collection is an array of the
|
654
|
+
// models' attributes.
|
655
|
+
toJSON: function(options) {
|
656
|
+
return this.map(function(model){ return model.toJSON(options); });
|
657
|
+
},
|
658
|
+
|
659
|
+
// Proxy `Backbone.sync` by default.
|
660
|
+
sync: function() {
|
661
|
+
return Backbone.sync.apply(this, arguments);
|
662
|
+
},
|
663
|
+
|
664
|
+
// Add a model, or list of models to the set.
|
665
|
+
add: function(models, options) {
|
666
|
+
return this.set(models, _.extend({merge: false}, options, addOptions));
|
667
|
+
},
|
668
|
+
|
669
|
+
// Remove a model, or a list of models from the set.
|
670
|
+
remove: function(models, options) {
|
671
|
+
var singular = !_.isArray(models);
|
672
|
+
models = singular ? [models] : _.clone(models);
|
673
|
+
options || (options = {});
|
674
|
+
for (var i = 0, length = models.length; i < length; i++) {
|
675
|
+
var model = models[i] = this.get(models[i]);
|
676
|
+
if (!model) continue;
|
677
|
+
var id = this.modelId(model.attributes);
|
678
|
+
if (id != null) delete this._byId[id];
|
679
|
+
delete this._byId[model.cid];
|
680
|
+
var index = this.indexOf(model);
|
681
|
+
this.models.splice(index, 1);
|
682
|
+
this.length--;
|
683
|
+
if (!options.silent) {
|
684
|
+
options.index = index;
|
685
|
+
model.trigger('remove', model, this, options);
|
686
|
+
}
|
687
|
+
this._removeReference(model, options);
|
688
|
+
}
|
689
|
+
return singular ? models[0] : models;
|
690
|
+
},
|
691
|
+
|
692
|
+
// Update a collection by `set`-ing a new list of models, adding new ones,
|
693
|
+
// removing models that are no longer present, and merging models that
|
694
|
+
// already exist in the collection, as necessary. Similar to **Model#set**,
|
695
|
+
// the core operation for updating the data contained by the collection.
|
696
|
+
set: function(models, options) {
|
697
|
+
options = _.defaults({}, options, setOptions);
|
698
|
+
if (options.parse) models = this.parse(models, options);
|
699
|
+
var singular = !_.isArray(models);
|
700
|
+
models = singular ? (models ? [models] : []) : models.slice();
|
701
|
+
var id, model, attrs, existing, sort;
|
702
|
+
var at = options.at;
|
703
|
+
if (at < 0) at += this.length + 1;
|
704
|
+
var sortable = this.comparator && (at == null) && options.sort !== false;
|
705
|
+
var sortAttr = _.isString(this.comparator) ? this.comparator : null;
|
706
|
+
var toAdd = [], toRemove = [], modelMap = {};
|
707
|
+
var add = options.add, merge = options.merge, remove = options.remove;
|
708
|
+
var order = !sortable && add && remove ? [] : false;
|
709
|
+
var orderChanged = false;
|
710
|
+
|
711
|
+
// Turn bare objects into model references, and prevent invalid models
|
712
|
+
// from being added.
|
713
|
+
for (var i = 0, length = models.length; i < length; i++) {
|
714
|
+
attrs = models[i];
|
715
|
+
|
716
|
+
// If a duplicate is found, prevent it from being added and
|
717
|
+
// optionally merge it into the existing model.
|
718
|
+
if (existing = this.get(attrs)) {
|
719
|
+
if (remove) modelMap[existing.cid] = true;
|
720
|
+
if (merge && attrs !== existing) {
|
721
|
+
attrs = this._isModel(attrs) ? attrs.attributes : attrs;
|
722
|
+
if (options.parse) attrs = existing.parse(attrs, options);
|
723
|
+
existing.set(attrs, options);
|
724
|
+
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
|
725
|
+
}
|
726
|
+
models[i] = existing;
|
727
|
+
|
728
|
+
// If this is a new, valid model, push it to the `toAdd` list.
|
729
|
+
} else if (add) {
|
730
|
+
model = models[i] = this._prepareModel(attrs, options);
|
731
|
+
if (!model) continue;
|
732
|
+
toAdd.push(model);
|
733
|
+
this._addReference(model, options);
|
734
|
+
}
|
735
|
+
|
736
|
+
// Do not add multiple models with the same `id`.
|
737
|
+
model = existing || model;
|
738
|
+
if (!model) continue;
|
739
|
+
id = this.modelId(model.attributes);
|
740
|
+
if (order && (model.isNew() || !modelMap[id])) {
|
741
|
+
order.push(model);
|
742
|
+
|
743
|
+
// Check to see if this is actually a new model at this index.
|
744
|
+
orderChanged = orderChanged || !this.models[i] || model.cid !== this.models[i].cid;
|
745
|
+
}
|
746
|
+
|
747
|
+
modelMap[id] = true;
|
748
|
+
}
|
749
|
+
|
750
|
+
// Remove nonexistent models if appropriate.
|
751
|
+
if (remove) {
|
752
|
+
for (var i = 0, length = this.length; i < length; i++) {
|
753
|
+
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
|
754
|
+
}
|
755
|
+
if (toRemove.length) this.remove(toRemove, options);
|
756
|
+
}
|
757
|
+
|
758
|
+
// See if sorting is needed, update `length` and splice in new models.
|
759
|
+
if (toAdd.length || orderChanged) {
|
760
|
+
if (sortable) sort = true;
|
761
|
+
this.length += toAdd.length;
|
762
|
+
if (at != null) {
|
763
|
+
for (var i = 0, length = toAdd.length; i < length; i++) {
|
764
|
+
this.models.splice(at + i, 0, toAdd[i]);
|
765
|
+
}
|
766
|
+
} else {
|
767
|
+
if (order) this.models.length = 0;
|
768
|
+
var orderedModels = order || toAdd;
|
769
|
+
for (var i = 0, length = orderedModels.length; i < length; i++) {
|
770
|
+
this.models.push(orderedModels[i]);
|
771
|
+
}
|
772
|
+
}
|
773
|
+
}
|
774
|
+
|
775
|
+
// Silently sort the collection if appropriate.
|
776
|
+
if (sort) this.sort({silent: true});
|
777
|
+
|
778
|
+
// Unless silenced, it's time to fire all appropriate add/sort events.
|
779
|
+
if (!options.silent) {
|
780
|
+
var addOpts = at != null ? _.clone(options) : options;
|
781
|
+
for (var i = 0, length = toAdd.length; i < length; i++) {
|
782
|
+
if (at != null) addOpts.index = at + i;
|
783
|
+
(model = toAdd[i]).trigger('add', model, this, addOpts);
|
784
|
+
}
|
785
|
+
if (sort || orderChanged) this.trigger('sort', this, options);
|
786
|
+
}
|
787
|
+
|
788
|
+
// Return the added (or merged) model (or models).
|
789
|
+
return singular ? models[0] : models;
|
790
|
+
},
|
791
|
+
|
792
|
+
// When you have more items than you want to add or remove individually,
|
793
|
+
// you can reset the entire set with a new list of models, without firing
|
794
|
+
// any granular `add` or `remove` events. Fires `reset` when finished.
|
795
|
+
// Useful for bulk operations and optimizations.
|
796
|
+
reset: function(models, options) {
|
797
|
+
options = options ? _.clone(options) : {};
|
798
|
+
for (var i = 0, length = this.models.length; i < length; i++) {
|
799
|
+
this._removeReference(this.models[i], options);
|
800
|
+
}
|
801
|
+
options.previousModels = this.models;
|
802
|
+
this._reset();
|
803
|
+
models = this.add(models, _.extend({silent: true}, options));
|
804
|
+
if (!options.silent) this.trigger('reset', this, options);
|
805
|
+
return models;
|
806
|
+
},
|
807
|
+
|
808
|
+
// Add a model to the end of the collection.
|
809
|
+
push: function(model, options) {
|
810
|
+
return this.add(model, _.extend({at: this.length}, options));
|
811
|
+
},
|
812
|
+
|
813
|
+
// Remove a model from the end of the collection.
|
814
|
+
pop: function(options) {
|
815
|
+
var model = this.at(this.length - 1);
|
816
|
+
this.remove(model, options);
|
817
|
+
return model;
|
818
|
+
},
|
819
|
+
|
820
|
+
// Add a model to the beginning of the collection.
|
821
|
+
unshift: function(model, options) {
|
822
|
+
return this.add(model, _.extend({at: 0}, options));
|
823
|
+
},
|
824
|
+
|
825
|
+
// Remove a model from the beginning of the collection.
|
826
|
+
shift: function(options) {
|
827
|
+
var model = this.at(0);
|
828
|
+
this.remove(model, options);
|
829
|
+
return model;
|
830
|
+
},
|
831
|
+
|
832
|
+
// Slice out a sub-array of models from the collection.
|
833
|
+
slice: function() {
|
834
|
+
return slice.apply(this.models, arguments);
|
835
|
+
},
|
836
|
+
|
837
|
+
// Get a model from the set by id.
|
838
|
+
get: function(obj) {
|
839
|
+
if (obj == null) return void 0;
|
840
|
+
var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
|
841
|
+
return this._byId[obj] || this._byId[id] || this._byId[obj.cid];
|
842
|
+
},
|
843
|
+
|
844
|
+
// Get the model at the given index.
|
845
|
+
at: function(index) {
|
846
|
+
if (index < 0) index += this.length;
|
847
|
+
return this.models[index];
|
848
|
+
},
|
849
|
+
|
850
|
+
// Return models with matching attributes. Useful for simple cases of
|
851
|
+
// `filter`.
|
852
|
+
where: function(attrs, first) {
|
853
|
+
var matches = _.matches(attrs);
|
854
|
+
return this[first ? 'find' : 'filter'](function(model) {
|
855
|
+
return matches(model.attributes);
|
856
|
+
});
|
857
|
+
},
|
858
|
+
|
859
|
+
// Return the first model with matching attributes. Useful for simple cases
|
860
|
+
// of `find`.
|
861
|
+
findWhere: function(attrs) {
|
862
|
+
return this.where(attrs, true);
|
863
|
+
},
|
864
|
+
|
865
|
+
// Force the collection to re-sort itself. You don't need to call this under
|
866
|
+
// normal circumstances, as the set will maintain sort order as each item
|
867
|
+
// is added.
|
868
|
+
sort: function(options) {
|
869
|
+
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
|
870
|
+
options || (options = {});
|
871
|
+
|
872
|
+
// Run sort based on type of `comparator`.
|
873
|
+
if (_.isString(this.comparator) || this.comparator.length === 1) {
|
874
|
+
this.models = this.sortBy(this.comparator, this);
|
875
|
+
} else {
|
876
|
+
this.models.sort(_.bind(this.comparator, this));
|
877
|
+
}
|
878
|
+
|
879
|
+
if (!options.silent) this.trigger('sort', this, options);
|
880
|
+
return this;
|
881
|
+
},
|
882
|
+
|
883
|
+
// Pluck an attribute from each model in the collection.
|
884
|
+
pluck: function(attr) {
|
885
|
+
return _.invoke(this.models, 'get', attr);
|
886
|
+
},
|
887
|
+
|
888
|
+
// Fetch the default set of models for this collection, resetting the
|
889
|
+
// collection when they arrive. If `reset: true` is passed, the response
|
890
|
+
// data will be passed through the `reset` method instead of `set`.
|
891
|
+
fetch: function(options) {
|
892
|
+
options = options ? _.clone(options) : {};
|
893
|
+
if (options.parse === void 0) options.parse = true;
|
894
|
+
var success = options.success;
|
895
|
+
var collection = this;
|
896
|
+
options.success = function(resp) {
|
897
|
+
var method = options.reset ? 'reset' : 'set';
|
898
|
+
collection[method](resp, options);
|
899
|
+
if (success) success(collection, resp, options);
|
900
|
+
collection.trigger('sync', collection, resp, options);
|
901
|
+
};
|
902
|
+
wrapError(this, options);
|
903
|
+
return this.sync('read', this, options);
|
904
|
+
},
|
905
|
+
|
906
|
+
// Create a new instance of a model in this collection. Add the model to the
|
907
|
+
// collection immediately, unless `wait: true` is passed, in which case we
|
908
|
+
// wait for the server to agree.
|
909
|
+
create: function(model, options) {
|
910
|
+
options = options ? _.clone(options) : {};
|
911
|
+
if (!(model = this._prepareModel(model, options))) return false;
|
912
|
+
if (!options.wait) this.add(model, options);
|
913
|
+
var collection = this;
|
914
|
+
var success = options.success;
|
915
|
+
options.success = function(model, resp) {
|
916
|
+
if (options.wait) collection.add(model, options);
|
917
|
+
if (success) success(model, resp, options);
|
918
|
+
};
|
919
|
+
model.save(null, options);
|
920
|
+
return model;
|
921
|
+
},
|
922
|
+
|
923
|
+
// **parse** converts a response into a list of models to be added to the
|
924
|
+
// collection. The default implementation is just to pass it through.
|
925
|
+
parse: function(resp, options) {
|
926
|
+
return resp;
|
927
|
+
},
|
928
|
+
|
929
|
+
// Create a new collection with an identical list of models as this one.
|
930
|
+
clone: function() {
|
931
|
+
return new this.constructor(this.models, {
|
932
|
+
model: this.model,
|
933
|
+
comparator: this.comparator
|
934
|
+
});
|
935
|
+
},
|
936
|
+
|
937
|
+
// Define how to uniquely identify models in the collection.
|
938
|
+
modelId: function (attrs) {
|
939
|
+
return attrs[this.model.prototype.idAttribute || 'id'];
|
940
|
+
},
|
941
|
+
|
942
|
+
// Private method to reset all internal state. Called when the collection
|
943
|
+
// is first initialized or reset.
|
944
|
+
_reset: function() {
|
945
|
+
this.length = 0;
|
946
|
+
this.models = [];
|
947
|
+
this._byId = {};
|
948
|
+
},
|
949
|
+
|
950
|
+
// Prepare a hash of attributes (or other model) to be added to this
|
951
|
+
// collection.
|
952
|
+
_prepareModel: function(attrs, options) {
|
953
|
+
if (this._isModel(attrs)) {
|
954
|
+
if (!attrs.collection) attrs.collection = this;
|
955
|
+
return attrs;
|
956
|
+
}
|
957
|
+
options = options ? _.clone(options) : {};
|
958
|
+
options.collection = this;
|
959
|
+
var model = new this.model(attrs, options);
|
960
|
+
if (!model.validationError) return model;
|
961
|
+
this.trigger('invalid', this, model.validationError, options);
|
962
|
+
return false;
|
963
|
+
},
|
964
|
+
|
965
|
+
// Method for checking whether an object should be considered a model for
|
966
|
+
// the purposes of adding to the collection.
|
967
|
+
_isModel: function (model) {
|
968
|
+
return model instanceof Model;
|
969
|
+
},
|
970
|
+
|
971
|
+
// Internal method to create a model's ties to a collection.
|
972
|
+
_addReference: function(model, options) {
|
973
|
+
this._byId[model.cid] = model;
|
974
|
+
var id = this.modelId(model.attributes);
|
975
|
+
if (id != null) this._byId[id] = model;
|
976
|
+
model.on('all', this._onModelEvent, this);
|
977
|
+
},
|
978
|
+
|
979
|
+
// Internal method to sever a model's ties to a collection.
|
980
|
+
_removeReference: function(model, options) {
|
981
|
+
if (this === model.collection) delete model.collection;
|
982
|
+
model.off('all', this._onModelEvent, this);
|
983
|
+
},
|
984
|
+
|
985
|
+
// Internal method called every time a model in the set fires an event.
|
986
|
+
// Sets need to update their indexes when models change ids. All other
|
987
|
+
// events simply proxy through. "add" and "remove" events that originate
|
988
|
+
// in other collections are ignored.
|
989
|
+
_onModelEvent: function(event, model, collection, options) {
|
990
|
+
if ((event === 'add' || event === 'remove') && collection !== this) return;
|
991
|
+
if (event === 'destroy') this.remove(model, options);
|
992
|
+
if (event === 'change') {
|
993
|
+
var prevId = this.modelId(model.previousAttributes());
|
994
|
+
var id = this.modelId(model.attributes);
|
995
|
+
if (prevId !== id) {
|
996
|
+
if (prevId != null) delete this._byId[prevId];
|
997
|
+
if (id != null) this._byId[id] = model;
|
998
|
+
}
|
999
|
+
}
|
1000
|
+
this.trigger.apply(this, arguments);
|
1001
|
+
}
|
1002
|
+
|
1003
|
+
});
|
1004
|
+
|
1005
|
+
// Underscore methods that we want to implement on the Collection.
|
1006
|
+
// 90% of the core usefulness of Backbone Collections is actually implemented
|
1007
|
+
// right here:
|
1008
|
+
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
|
1009
|
+
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
|
1010
|
+
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
|
1011
|
+
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
|
1012
|
+
'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
|
1013
|
+
'lastIndexOf', 'isEmpty', 'chain', 'sample', 'partition'];
|
1014
|
+
|
1015
|
+
// Mix in each Underscore method as a proxy to `Collection#models`.
|
1016
|
+
_.each(methods, function(method) {
|
1017
|
+
if (!_[method]) return;
|
1018
|
+
Collection.prototype[method] = function() {
|
1019
|
+
var args = slice.call(arguments);
|
1020
|
+
args.unshift(this.models);
|
1021
|
+
return _[method].apply(_, args);
|
1022
|
+
};
|
1023
|
+
});
|
1024
|
+
|
1025
|
+
// Underscore methods that take a property name as an argument.
|
1026
|
+
var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
|
1027
|
+
|
1028
|
+
// Use attributes instead of properties.
|
1029
|
+
_.each(attributeMethods, function(method) {
|
1030
|
+
if (!_[method]) return;
|
1031
|
+
Collection.prototype[method] = function(value, context) {
|
1032
|
+
var iterator = _.isFunction(value) ? value : function(model) {
|
1033
|
+
return model.get(value);
|
1034
|
+
};
|
1035
|
+
return _[method](this.models, iterator, context);
|
1036
|
+
};
|
1037
|
+
});
|
1038
|
+
|
1039
|
+
// Backbone.View
|
1040
|
+
// -------------
|
1041
|
+
|
1042
|
+
// Backbone Views are almost more convention than they are actual code. A View
|
1043
|
+
// is simply a JavaScript object that represents a logical chunk of UI in the
|
1044
|
+
// DOM. This might be a single item, an entire list, a sidebar or panel, or
|
1045
|
+
// even the surrounding frame which wraps your whole app. Defining a chunk of
|
1046
|
+
// UI as a **View** allows you to define your DOM events declaratively, without
|
1047
|
+
// having to worry about render order ... and makes it easy for the view to
|
1048
|
+
// react to specific changes in the state of your models.
|
1049
|
+
|
1050
|
+
// Creating a Backbone.View creates its initial element outside of the DOM,
|
1051
|
+
// if an existing element is not provided...
|
1052
|
+
var View = Backbone.View = function(options) {
|
1053
|
+
this.cid = _.uniqueId('view');
|
1054
|
+
options || (options = {});
|
1055
|
+
_.extend(this, _.pick(options, viewOptions));
|
1056
|
+
this._ensureElement();
|
1057
|
+
this.initialize.apply(this, arguments);
|
1058
|
+
};
|
1059
|
+
|
1060
|
+
// Cached regex to split keys for `delegate`.
|
1061
|
+
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
|
1062
|
+
|
1063
|
+
// List of view options to be merged as properties.
|
1064
|
+
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
|
1065
|
+
|
1066
|
+
// Set up all inheritable **Backbone.View** properties and methods.
|
1067
|
+
_.extend(View.prototype, Events, {
|
1068
|
+
|
1069
|
+
// The default `tagName` of a View's element is `"div"`.
|
1070
|
+
tagName: 'div',
|
1071
|
+
|
1072
|
+
// jQuery delegate for element lookup, scoped to DOM elements within the
|
1073
|
+
// current view. This should be preferred to global lookups where possible.
|
1074
|
+
$: function(selector) {
|
1075
|
+
return this.$el.find(selector);
|
1076
|
+
},
|
1077
|
+
|
1078
|
+
// Initialize is an empty function by default. Override it with your own
|
1079
|
+
// initialization logic.
|
1080
|
+
initialize: function(){},
|
1081
|
+
|
1082
|
+
// **render** is the core function that your view should override, in order
|
1083
|
+
// to populate its element (`this.el`), with the appropriate HTML. The
|
1084
|
+
// convention is for **render** to always return `this`.
|
1085
|
+
render: function() {
|
1086
|
+
return this;
|
1087
|
+
},
|
1088
|
+
|
1089
|
+
// Remove this view by taking the element out of the DOM, and removing any
|
1090
|
+
// applicable Backbone.Events listeners.
|
1091
|
+
remove: function() {
|
1092
|
+
this._removeElement();
|
1093
|
+
this.stopListening();
|
1094
|
+
return this;
|
1095
|
+
},
|
1096
|
+
|
1097
|
+
// Remove this view's element from the document and all event listeners
|
1098
|
+
// attached to it. Exposed for subclasses using an alternative DOM
|
1099
|
+
// manipulation API.
|
1100
|
+
_removeElement: function() {
|
1101
|
+
this.$el.remove();
|
1102
|
+
},
|
1103
|
+
|
1104
|
+
// Change the view's element (`this.el` property) and re-delegate the
|
1105
|
+
// view's events on the new element.
|
1106
|
+
setElement: function(element) {
|
1107
|
+
this.undelegateEvents();
|
1108
|
+
this._setElement(element);
|
1109
|
+
this.delegateEvents();
|
1110
|
+
return this;
|
1111
|
+
},
|
1112
|
+
|
1113
|
+
// Creates the `this.el` and `this.$el` references for this view using the
|
1114
|
+
// given `el`. `el` can be a CSS selector or an HTML string, a jQuery
|
1115
|
+
// context or an element. Subclasses can override this to utilize an
|
1116
|
+
// alternative DOM manipulation API and are only required to set the
|
1117
|
+
// `this.el` property.
|
1118
|
+
_setElement: function(el) {
|
1119
|
+
this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
|
1120
|
+
this.el = this.$el[0];
|
1121
|
+
},
|
1122
|
+
|
1123
|
+
// Set callbacks, where `this.events` is a hash of
|
1124
|
+
//
|
1125
|
+
// *{"event selector": "callback"}*
|
1126
|
+
//
|
1127
|
+
// {
|
1128
|
+
// 'mousedown .title': 'edit',
|
1129
|
+
// 'click .button': 'save',
|
1130
|
+
// 'click .open': function(e) { ... }
|
1131
|
+
// }
|
1132
|
+
//
|
1133
|
+
// pairs. Callbacks will be bound to the view, with `this` set properly.
|
1134
|
+
// Uses event delegation for efficiency.
|
1135
|
+
// Omitting the selector binds the event to `this.el`.
|
1136
|
+
delegateEvents: function(events) {
|
1137
|
+
if (!(events || (events = _.result(this, 'events')))) return this;
|
1138
|
+
this.undelegateEvents();
|
1139
|
+
for (var key in events) {
|
1140
|
+
var method = events[key];
|
1141
|
+
if (!_.isFunction(method)) method = this[events[key]];
|
1142
|
+
if (!method) continue;
|
1143
|
+
var match = key.match(delegateEventSplitter);
|
1144
|
+
this.delegate(match[1], match[2], _.bind(method, this));
|
1145
|
+
}
|
1146
|
+
return this;
|
1147
|
+
},
|
1148
|
+
|
1149
|
+
// Add a single event listener to the view's element (or a child element
|
1150
|
+
// using `selector`). This only works for delegate-able events: not `focus`,
|
1151
|
+
// `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
|
1152
|
+
delegate: function(eventName, selector, listener) {
|
1153
|
+
this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
|
1154
|
+
},
|
1155
|
+
|
1156
|
+
// Clears all callbacks previously bound to the view by `delegateEvents`.
|
1157
|
+
// You usually don't need to use this, but may wish to if you have multiple
|
1158
|
+
// Backbone views attached to the same DOM element.
|
1159
|
+
undelegateEvents: function() {
|
1160
|
+
if (this.$el) this.$el.off('.delegateEvents' + this.cid);
|
1161
|
+
return this;
|
1162
|
+
},
|
1163
|
+
|
1164
|
+
// A finer-grained `undelegateEvents` for removing a single delegated event.
|
1165
|
+
// `selector` and `listener` are both optional.
|
1166
|
+
undelegate: function(eventName, selector, listener) {
|
1167
|
+
this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
|
1168
|
+
},
|
1169
|
+
|
1170
|
+
// Produces a DOM element to be assigned to your view. Exposed for
|
1171
|
+
// subclasses using an alternative DOM manipulation API.
|
1172
|
+
_createElement: function(tagName) {
|
1173
|
+
return document.createElement(tagName);
|
1174
|
+
},
|
1175
|
+
|
1176
|
+
// Ensure that the View has a DOM element to render into.
|
1177
|
+
// If `this.el` is a string, pass it through `$()`, take the first
|
1178
|
+
// matching element, and re-assign it to `el`. Otherwise, create
|
1179
|
+
// an element from the `id`, `className` and `tagName` properties.
|
1180
|
+
_ensureElement: function() {
|
1181
|
+
if (!this.el) {
|
1182
|
+
var attrs = _.extend({}, _.result(this, 'attributes'));
|
1183
|
+
if (this.id) attrs.id = _.result(this, 'id');
|
1184
|
+
if (this.className) attrs['class'] = _.result(this, 'className');
|
1185
|
+
this.setElement(this._createElement(_.result(this, 'tagName')));
|
1186
|
+
this._setAttributes(attrs);
|
1187
|
+
} else {
|
1188
|
+
this.setElement(_.result(this, 'el'));
|
1189
|
+
}
|
1190
|
+
},
|
1191
|
+
|
1192
|
+
// Set attributes from a hash on this view's element. Exposed for
|
1193
|
+
// subclasses using an alternative DOM manipulation API.
|
1194
|
+
_setAttributes: function(attributes) {
|
1195
|
+
this.$el.attr(attributes);
|
1196
|
+
}
|
1197
|
+
|
1198
|
+
});
|
1199
|
+
|
1200
|
+
// Backbone.sync
|
1201
|
+
// -------------
|
1202
|
+
|
1203
|
+
// Override this function to change the manner in which Backbone persists
|
1204
|
+
// models to the server. You will be passed the type of request, and the
|
1205
|
+
// model in question. By default, makes a RESTful Ajax request
|
1206
|
+
// to the model's `url()`. Some possible customizations could be:
|
1207
|
+
//
|
1208
|
+
// * Use `setTimeout` to batch rapid-fire updates into a single request.
|
1209
|
+
// * Send up the models as XML instead of JSON.
|
1210
|
+
// * Persist models via WebSockets instead of Ajax.
|
1211
|
+
//
|
1212
|
+
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
|
1213
|
+
// as `POST`, with a `_method` parameter containing the true HTTP method,
|
1214
|
+
// as well as all requests with the body as `application/x-www-form-urlencoded`
|
1215
|
+
// instead of `application/json` with the model in a param named `model`.
|
1216
|
+
// Useful when interfacing with server-side languages like **PHP** that make
|
1217
|
+
// it difficult to read the body of `PUT` requests.
|
1218
|
+
Backbone.sync = function(method, model, options) {
|
1219
|
+
var type = methodMap[method];
|
1220
|
+
|
1221
|
+
// Default options, unless specified.
|
1222
|
+
_.defaults(options || (options = {}), {
|
1223
|
+
emulateHTTP: Backbone.emulateHTTP,
|
1224
|
+
emulateJSON: Backbone.emulateJSON
|
1225
|
+
});
|
1226
|
+
|
1227
|
+
// Default JSON-request options.
|
1228
|
+
var params = {type: type, dataType: 'json'};
|
1229
|
+
|
1230
|
+
// Ensure that we have a URL.
|
1231
|
+
if (!options.url) {
|
1232
|
+
params.url = _.result(model, 'url') || urlError();
|
1233
|
+
}
|
1234
|
+
|
1235
|
+
// Ensure that we have the appropriate request data.
|
1236
|
+
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
|
1237
|
+
params.contentType = 'application/json';
|
1238
|
+
params.data = JSON.stringify(options.attrs || model.toJSON(options));
|
1239
|
+
}
|
1240
|
+
|
1241
|
+
// For older servers, emulate JSON by encoding the request into an HTML-form.
|
1242
|
+
if (options.emulateJSON) {
|
1243
|
+
params.contentType = 'application/x-www-form-urlencoded';
|
1244
|
+
params.data = params.data ? {model: params.data} : {};
|
1245
|
+
}
|
1246
|
+
|
1247
|
+
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
|
1248
|
+
// And an `X-HTTP-Method-Override` header.
|
1249
|
+
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
|
1250
|
+
params.type = 'POST';
|
1251
|
+
if (options.emulateJSON) params.data._method = type;
|
1252
|
+
var beforeSend = options.beforeSend;
|
1253
|
+
options.beforeSend = function(xhr) {
|
1254
|
+
xhr.setRequestHeader('X-HTTP-Method-Override', type);
|
1255
|
+
if (beforeSend) return beforeSend.apply(this, arguments);
|
1256
|
+
};
|
1257
|
+
}
|
1258
|
+
|
1259
|
+
// Don't process data on a non-GET request.
|
1260
|
+
if (params.type !== 'GET' && !options.emulateJSON) {
|
1261
|
+
params.processData = false;
|
1262
|
+
}
|
1263
|
+
|
1264
|
+
// Pass along `textStatus` and `errorThrown` from jQuery.
|
1265
|
+
var error = options.error;
|
1266
|
+
options.error = function(xhr, textStatus, errorThrown) {
|
1267
|
+
options.textStatus = textStatus;
|
1268
|
+
options.errorThrown = errorThrown;
|
1269
|
+
if (error) error.apply(this, arguments);
|
1270
|
+
};
|
1271
|
+
|
1272
|
+
// Make the request, allowing the user to override any Ajax options.
|
1273
|
+
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
|
1274
|
+
model.trigger('request', model, xhr, options);
|
1275
|
+
return xhr;
|
1276
|
+
};
|
1277
|
+
|
1278
|
+
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
|
1279
|
+
var methodMap = {
|
1280
|
+
'create': 'POST',
|
1281
|
+
'update': 'PUT',
|
1282
|
+
'patch': 'PATCH',
|
1283
|
+
'delete': 'DELETE',
|
1284
|
+
'read': 'GET'
|
1285
|
+
};
|
1286
|
+
|
1287
|
+
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
|
1288
|
+
// Override this if you'd like to use a different library.
|
1289
|
+
Backbone.ajax = function() {
|
1290
|
+
return Backbone.$.ajax.apply(Backbone.$, arguments);
|
1291
|
+
};
|
1292
|
+
|
1293
|
+
// Backbone.Router
|
1294
|
+
// ---------------
|
1295
|
+
|
1296
|
+
// Routers map faux-URLs to actions, and fire events when routes are
|
1297
|
+
// matched. Creating a new one sets its `routes` hash, if not set statically.
|
1298
|
+
var Router = Backbone.Router = function(options) {
|
1299
|
+
options || (options = {});
|
1300
|
+
if (options.routes) this.routes = options.routes;
|
1301
|
+
this._bindRoutes();
|
1302
|
+
this.initialize.apply(this, arguments);
|
1303
|
+
};
|
1304
|
+
|
1305
|
+
// Cached regular expressions for matching named param parts and splatted
|
1306
|
+
// parts of route strings.
|
1307
|
+
var optionalParam = /\((.*?)\)/g;
|
1308
|
+
var namedParam = /(\(\?)?:\w+/g;
|
1309
|
+
var splatParam = /\*\w+/g;
|
1310
|
+
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
|
1311
|
+
|
1312
|
+
// Set up all inheritable **Backbone.Router** properties and methods.
|
1313
|
+
_.extend(Router.prototype, Events, {
|
1314
|
+
|
1315
|
+
// Initialize is an empty function by default. Override it with your own
|
1316
|
+
// initialization logic.
|
1317
|
+
initialize: function(){},
|
1318
|
+
|
1319
|
+
// Manually bind a single named route to a callback. For example:
|
1320
|
+
//
|
1321
|
+
// this.route('search/:query/p:num', 'search', function(query, num) {
|
1322
|
+
// ...
|
1323
|
+
// });
|
1324
|
+
//
|
1325
|
+
route: function(route, name, callback) {
|
1326
|
+
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
|
1327
|
+
if (_.isFunction(name)) {
|
1328
|
+
callback = name;
|
1329
|
+
name = '';
|
1330
|
+
}
|
1331
|
+
if (!callback) callback = this[name];
|
1332
|
+
var router = this;
|
1333
|
+
Backbone.history.route(route, function(fragment) {
|
1334
|
+
var args = router._extractParameters(route, fragment);
|
1335
|
+
if (router.execute(callback, args, name) !== false) {
|
1336
|
+
router.trigger.apply(router, ['route:' + name].concat(args));
|
1337
|
+
router.trigger('route', name, args);
|
1338
|
+
Backbone.history.trigger('route', router, name, args);
|
1339
|
+
}
|
1340
|
+
});
|
1341
|
+
return this;
|
1342
|
+
},
|
1343
|
+
|
1344
|
+
// Execute a route handler with the provided parameters. This is an
|
1345
|
+
// excellent place to do pre-route setup or post-route cleanup.
|
1346
|
+
execute: function(callback, args, name) {
|
1347
|
+
if (callback) callback.apply(this, args);
|
1348
|
+
},
|
1349
|
+
|
1350
|
+
// Simple proxy to `Backbone.history` to save a fragment into the history.
|
1351
|
+
navigate: function(fragment, options) {
|
1352
|
+
Backbone.history.navigate(fragment, options);
|
1353
|
+
return this;
|
1354
|
+
},
|
1355
|
+
|
1356
|
+
// Bind all defined routes to `Backbone.history`. We have to reverse the
|
1357
|
+
// order of the routes here to support behavior where the most general
|
1358
|
+
// routes can be defined at the bottom of the route map.
|
1359
|
+
_bindRoutes: function() {
|
1360
|
+
if (!this.routes) return;
|
1361
|
+
this.routes = _.result(this, 'routes');
|
1362
|
+
var route, routes = _.keys(this.routes);
|
1363
|
+
while ((route = routes.pop()) != null) {
|
1364
|
+
this.route(route, this.routes[route]);
|
1365
|
+
}
|
1366
|
+
},
|
1367
|
+
|
1368
|
+
// Convert a route string into a regular expression, suitable for matching
|
1369
|
+
// against the current location hash.
|
1370
|
+
_routeToRegExp: function(route) {
|
1371
|
+
route = route.replace(escapeRegExp, '\\$&')
|
1372
|
+
.replace(optionalParam, '(?:$1)?')
|
1373
|
+
.replace(namedParam, function(match, optional) {
|
1374
|
+
return optional ? match : '([^/?]+)';
|
1375
|
+
})
|
1376
|
+
.replace(splatParam, '([^?]*?)');
|
1377
|
+
return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
|
1378
|
+
},
|
1379
|
+
|
1380
|
+
// Given a route, and a URL fragment that it matches, return the array of
|
1381
|
+
// extracted decoded parameters. Empty or unmatched parameters will be
|
1382
|
+
// treated as `null` to normalize cross-browser behavior.
|
1383
|
+
_extractParameters: function(route, fragment) {
|
1384
|
+
var params = route.exec(fragment).slice(1);
|
1385
|
+
return _.map(params, function(param, i) {
|
1386
|
+
// Don't decode the search params.
|
1387
|
+
if (i === params.length - 1) return param || null;
|
1388
|
+
return param ? decodeURIComponent(param) : null;
|
1389
|
+
});
|
1390
|
+
}
|
1391
|
+
|
1392
|
+
});
|
1393
|
+
|
1394
|
+
// Backbone.History
|
1395
|
+
// ----------------
|
1396
|
+
|
1397
|
+
// Handles cross-browser history management, based on either
|
1398
|
+
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
|
1399
|
+
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
|
1400
|
+
// and URL fragments. If the browser supports neither (old IE, natch),
|
1401
|
+
// falls back to polling.
|
1402
|
+
var History = Backbone.History = function() {
|
1403
|
+
this.handlers = [];
|
1404
|
+
_.bindAll(this, 'checkUrl');
|
1405
|
+
|
1406
|
+
// Ensure that `History` can be used outside of the browser.
|
1407
|
+
if (typeof window !== 'undefined') {
|
1408
|
+
this.location = window.location;
|
1409
|
+
this.history = window.history;
|
1410
|
+
}
|
1411
|
+
};
|
1412
|
+
|
1413
|
+
// Cached regex for stripping a leading hash/slash and trailing space.
|
1414
|
+
var routeStripper = /^[#\/]|\s+$/g;
|
1415
|
+
|
1416
|
+
// Cached regex for stripping leading and trailing slashes.
|
1417
|
+
var rootStripper = /^\/+|\/+$/g;
|
1418
|
+
|
1419
|
+
// Cached regex for stripping urls of hash.
|
1420
|
+
var pathStripper = /#.*$/;
|
1421
|
+
|
1422
|
+
// Has the history handling already been started?
|
1423
|
+
History.started = false;
|
1424
|
+
|
1425
|
+
// Set up all inheritable **Backbone.History** properties and methods.
|
1426
|
+
_.extend(History.prototype, Events, {
|
1427
|
+
|
1428
|
+
// The default interval to poll for hash changes, if necessary, is
|
1429
|
+
// twenty times a second.
|
1430
|
+
interval: 50,
|
1431
|
+
|
1432
|
+
// Are we at the app root?
|
1433
|
+
atRoot: function() {
|
1434
|
+
var path = this.location.pathname.replace(/[^\/]$/, '$&/');
|
1435
|
+
return path === this.root && !this.getSearch();
|
1436
|
+
},
|
1437
|
+
|
1438
|
+
// In IE6, the hash fragment and search params are incorrect if the
|
1439
|
+
// fragment contains `?`.
|
1440
|
+
getSearch: function() {
|
1441
|
+
var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
|
1442
|
+
return match ? match[0] : '';
|
1443
|
+
},
|
1444
|
+
|
1445
|
+
// Gets the true hash value. Cannot use location.hash directly due to bug
|
1446
|
+
// in Firefox where location.hash will always be decoded.
|
1447
|
+
getHash: function(window) {
|
1448
|
+
var match = (window || this).location.href.match(/#(.*)$/);
|
1449
|
+
return match ? match[1] : '';
|
1450
|
+
},
|
1451
|
+
|
1452
|
+
// Get the pathname and search params, without the root.
|
1453
|
+
getPath: function() {
|
1454
|
+
var path = decodeURI(this.location.pathname + this.getSearch());
|
1455
|
+
var root = this.root.slice(0, -1);
|
1456
|
+
if (!path.indexOf(root)) path = path.slice(root.length);
|
1457
|
+
return path.slice(1);
|
1458
|
+
},
|
1459
|
+
|
1460
|
+
// Get the cross-browser normalized URL fragment from the path or hash.
|
1461
|
+
getFragment: function(fragment) {
|
1462
|
+
if (fragment == null) {
|
1463
|
+
if (this._hasPushState || !this._wantsHashChange) {
|
1464
|
+
fragment = this.getPath();
|
1465
|
+
} else {
|
1466
|
+
fragment = this.getHash();
|
1467
|
+
}
|
1468
|
+
}
|
1469
|
+
return fragment.replace(routeStripper, '');
|
1470
|
+
},
|
1471
|
+
|
1472
|
+
// Start the hash change handling, returning `true` if the current URL matches
|
1473
|
+
// an existing route, and `false` otherwise.
|
1474
|
+
start: function(options) {
|
1475
|
+
if (History.started) throw new Error('Backbone.history has already been started');
|
1476
|
+
History.started = true;
|
1477
|
+
|
1478
|
+
// Figure out the initial configuration. Do we need an iframe?
|
1479
|
+
// Is pushState desired ... is it available?
|
1480
|
+
this.options = _.extend({root: '/'}, this.options, options);
|
1481
|
+
this.root = this.options.root;
|
1482
|
+
this._wantsHashChange = this.options.hashChange !== false;
|
1483
|
+
this._hasHashChange = 'onhashchange' in window;
|
1484
|
+
this._wantsPushState = !!this.options.pushState;
|
1485
|
+
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
|
1486
|
+
this.fragment = this.getFragment();
|
1487
|
+
|
1488
|
+
// Add a cross-platform `addEventListener` shim for older browsers.
|
1489
|
+
var addEventListener = window.addEventListener || function (eventName, listener) {
|
1490
|
+
return attachEvent('on' + eventName, listener);
|
1491
|
+
};
|
1492
|
+
|
1493
|
+
// Normalize root to always include a leading and trailing slash.
|
1494
|
+
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
|
1495
|
+
|
1496
|
+
// Proxy an iframe to handle location events if the browser doesn't
|
1497
|
+
// support the `hashchange` event, HTML5 history, or the user wants
|
1498
|
+
// `hashChange` but not `pushState`.
|
1499
|
+
if (!this._hasHashChange && this._wantsHashChange && (!this._wantsPushState || !this._hasPushState)) {
|
1500
|
+
var iframe = document.createElement('iframe');
|
1501
|
+
iframe.src = 'javascript:0';
|
1502
|
+
iframe.style.display = 'none';
|
1503
|
+
iframe.tabIndex = -1;
|
1504
|
+
var body = document.body;
|
1505
|
+
// Using `appendChild` will throw on IE < 9 if the document is not ready.
|
1506
|
+
this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow;
|
1507
|
+
this.navigate(this.fragment);
|
1508
|
+
}
|
1509
|
+
|
1510
|
+
// Depending on whether we're using pushState or hashes, and whether
|
1511
|
+
// 'onhashchange' is supported, determine how we check the URL state.
|
1512
|
+
if (this._hasPushState) {
|
1513
|
+
addEventListener('popstate', this.checkUrl, false);
|
1514
|
+
} else if (this._wantsHashChange && this._hasHashChange && !this.iframe) {
|
1515
|
+
addEventListener('hashchange', this.checkUrl, false);
|
1516
|
+
} else if (this._wantsHashChange) {
|
1517
|
+
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
|
1518
|
+
}
|
1519
|
+
|
1520
|
+
// Transition from hashChange to pushState or vice versa if both are
|
1521
|
+
// requested.
|
1522
|
+
if (this._wantsHashChange && this._wantsPushState) {
|
1523
|
+
|
1524
|
+
// If we've started off with a route from a `pushState`-enabled
|
1525
|
+
// browser, but we're currently in a browser that doesn't support it...
|
1526
|
+
if (!this._hasPushState && !this.atRoot()) {
|
1527
|
+
this.location.replace(this.root + '#' + this.getPath());
|
1528
|
+
// Return immediately as browser will do redirect to new url
|
1529
|
+
return true;
|
1530
|
+
|
1531
|
+
// Or if we've started out with a hash-based route, but we're currently
|
1532
|
+
// in a browser where it could be `pushState`-based instead...
|
1533
|
+
} else if (this._hasPushState && this.atRoot()) {
|
1534
|
+
this.navigate(this.getHash(), {replace: true});
|
1535
|
+
}
|
1536
|
+
|
1537
|
+
}
|
1538
|
+
|
1539
|
+
if (!this.options.silent) return this.loadUrl();
|
1540
|
+
},
|
1541
|
+
|
1542
|
+
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
|
1543
|
+
// but possibly useful for unit testing Routers.
|
1544
|
+
stop: function() {
|
1545
|
+
// Add a cross-platform `removeEventListener` shim for older browsers.
|
1546
|
+
var removeEventListener = window.removeEventListener || function (eventName, listener) {
|
1547
|
+
return detachEvent('on' + eventName, listener);
|
1548
|
+
};
|
1549
|
+
|
1550
|
+
// Remove window listeners.
|
1551
|
+
if (this._hasPushState) {
|
1552
|
+
removeEventListener('popstate', this.checkUrl, false);
|
1553
|
+
} else if (this._wantsHashChange && this._hasHashChange && !this.iframe) {
|
1554
|
+
removeEventListener('hashchange', this.checkUrl, false);
|
1555
|
+
}
|
1556
|
+
|
1557
|
+
// Clean up the iframe if necessary.
|
1558
|
+
if (this.iframe) {
|
1559
|
+
document.body.removeChild(this.iframe.frameElement);
|
1560
|
+
this.iframe = null;
|
1561
|
+
}
|
1562
|
+
|
1563
|
+
// Some environments will throw when clearing an undefined interval.
|
1564
|
+
if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
|
1565
|
+
History.started = false;
|
1566
|
+
},
|
1567
|
+
|
1568
|
+
// Add a route to be tested when the fragment changes. Routes added later
|
1569
|
+
// may override previous routes.
|
1570
|
+
route: function(route, callback) {
|
1571
|
+
this.handlers.unshift({route: route, callback: callback});
|
1572
|
+
},
|
1573
|
+
|
1574
|
+
// Checks the current URL to see if it has changed, and if it has,
|
1575
|
+
// calls `loadUrl`, normalizing across the hidden iframe.
|
1576
|
+
checkUrl: function(e) {
|
1577
|
+
var current = this.getFragment();
|
1578
|
+
if (current === this.fragment && this.iframe) {
|
1579
|
+
current = this.getHash(this.iframe);
|
1580
|
+
}
|
1581
|
+
if (current === this.fragment) return false;
|
1582
|
+
if (this.iframe) this.navigate(current);
|
1583
|
+
this.loadUrl();
|
1584
|
+
},
|
1585
|
+
|
1586
|
+
// Attempt to load the current URL fragment. If a route succeeds with a
|
1587
|
+
// match, returns `true`. If no defined routes matches the fragment,
|
1588
|
+
// returns `false`.
|
1589
|
+
loadUrl: function(fragment) {
|
1590
|
+
fragment = this.fragment = this.getFragment(fragment);
|
1591
|
+
return _.any(this.handlers, function(handler) {
|
1592
|
+
if (handler.route.test(fragment)) {
|
1593
|
+
handler.callback(fragment);
|
1594
|
+
return true;
|
1595
|
+
}
|
1596
|
+
});
|
1597
|
+
},
|
1598
|
+
|
1599
|
+
// Save a fragment into the hash history, or replace the URL state if the
|
1600
|
+
// 'replace' option is passed. You are responsible for properly URL-encoding
|
1601
|
+
// the fragment in advance.
|
1602
|
+
//
|
1603
|
+
// The options object can contain `trigger: true` if you wish to have the
|
1604
|
+
// route callback be fired (not usually desirable), or `replace: true`, if
|
1605
|
+
// you wish to modify the current URL without adding an entry to the history.
|
1606
|
+
navigate: function(fragment, options) {
|
1607
|
+
if (!History.started) return false;
|
1608
|
+
if (!options || options === true) options = {trigger: !!options};
|
1609
|
+
|
1610
|
+
// Normalize the fragment.
|
1611
|
+
fragment = this.getFragment(fragment || '');
|
1612
|
+
|
1613
|
+
// Don't include a trailing slash on the root.
|
1614
|
+
var root = this.root;
|
1615
|
+
if (fragment === '' || fragment.charAt(0) === '?') {
|
1616
|
+
root = root.slice(0, -1) || '/';
|
1617
|
+
}
|
1618
|
+
var url = root + fragment;
|
1619
|
+
|
1620
|
+
// Strip the hash and decode for matching.
|
1621
|
+
fragment = decodeURI(fragment.replace(pathStripper, ''));
|
1622
|
+
|
1623
|
+
if (this.fragment === fragment) return;
|
1624
|
+
this.fragment = fragment;
|
1625
|
+
|
1626
|
+
// If pushState is available, we use it to set the fragment as a real URL.
|
1627
|
+
if (this._hasPushState) {
|
1628
|
+
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
|
1629
|
+
|
1630
|
+
// If hash changes haven't been explicitly disabled, update the hash
|
1631
|
+
// fragment to store history.
|
1632
|
+
} else if (this._wantsHashChange) {
|
1633
|
+
this._updateHash(this.location, fragment, options.replace);
|
1634
|
+
if (this.iframe && (fragment !== this.getHash(this.iframe))) {
|
1635
|
+
// Opening and closing the iframe tricks IE7 and earlier to push a
|
1636
|
+
// history entry on hash-tag change. When replace is true, we don't
|
1637
|
+
// want this.
|
1638
|
+
if(!options.replace) this.iframe.document.open().close();
|
1639
|
+
this._updateHash(this.iframe.location, fragment, options.replace);
|
1640
|
+
}
|
1641
|
+
|
1642
|
+
// If you've told us that you explicitly don't want fallback hashchange-
|
1643
|
+
// based history, then `navigate` becomes a page refresh.
|
1644
|
+
} else {
|
1645
|
+
return this.location.assign(url);
|
1646
|
+
}
|
1647
|
+
if (options.trigger) return this.loadUrl(fragment);
|
1648
|
+
},
|
1649
|
+
|
1650
|
+
// Update the hash location, either replacing the current entry, or adding
|
1651
|
+
// a new one to the browser history.
|
1652
|
+
_updateHash: function(location, fragment, replace) {
|
1653
|
+
if (replace) {
|
1654
|
+
var href = location.href.replace(/(javascript:|#).*$/, '');
|
1655
|
+
location.replace(href + '#' + fragment);
|
1656
|
+
} else {
|
1657
|
+
// Some browsers require that `hash` contains a leading #.
|
1658
|
+
location.hash = '#' + fragment;
|
1659
|
+
}
|
1660
|
+
}
|
1661
|
+
|
1662
|
+
});
|
1663
|
+
|
1664
|
+
// Create the default Backbone.history.
|
1665
|
+
Backbone.history = new History;
|
1666
|
+
|
1667
|
+
// Helpers
|
1668
|
+
// -------
|
1669
|
+
|
1670
|
+
// Helper function to correctly set up the prototype chain, for subclasses.
|
1671
|
+
// Similar to `goog.inherits`, but uses a hash of prototype properties and
|
1672
|
+
// class properties to be extended.
|
1673
|
+
var extend = function(protoProps, staticProps) {
|
1674
|
+
var parent = this;
|
1675
|
+
var child;
|
1676
|
+
|
1677
|
+
// The constructor function for the new subclass is either defined by you
|
1678
|
+
// (the "constructor" property in your `extend` definition), or defaulted
|
1679
|
+
// by us to simply call the parent's constructor.
|
1680
|
+
if (protoProps && _.has(protoProps, 'constructor')) {
|
1681
|
+
child = protoProps.constructor;
|
1682
|
+
} else {
|
1683
|
+
child = function(){ return parent.apply(this, arguments); };
|
1684
|
+
}
|
1685
|
+
|
1686
|
+
// Add static properties to the constructor function, if supplied.
|
1687
|
+
_.extend(child, parent, staticProps);
|
1688
|
+
|
1689
|
+
// Set the prototype chain to inherit from `parent`, without calling
|
1690
|
+
// `parent`'s constructor function.
|
1691
|
+
var Surrogate = function(){ this.constructor = child; };
|
1692
|
+
Surrogate.prototype = parent.prototype;
|
1693
|
+
child.prototype = new Surrogate;
|
1694
|
+
|
1695
|
+
// Add prototype properties (instance properties) to the subclass,
|
1696
|
+
// if supplied.
|
1697
|
+
if (protoProps) _.extend(child.prototype, protoProps);
|
1698
|
+
|
1699
|
+
// Set a convenience property in case the parent's prototype is needed
|
1700
|
+
// later.
|
1701
|
+
child.__super__ = parent.prototype;
|
1702
|
+
|
1703
|
+
return child;
|
1704
|
+
};
|
1705
|
+
|
1706
|
+
// Set up inheritance for the model, collection, router, view and history.
|
1707
|
+
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
|
1708
|
+
|
1709
|
+
// Throw an error when a URL is needed, and none is supplied.
|
1710
|
+
var urlError = function() {
|
1711
|
+
throw new Error('A "url" property or function must be specified');
|
1712
|
+
};
|
1713
|
+
|
1714
|
+
// Wrap an optional error callback with a fallback error event.
|
1715
|
+
var wrapError = function(model, options) {
|
1716
|
+
var error = options.error;
|
1717
|
+
options.error = function(resp) {
|
1718
|
+
if (error) error(model, resp, options);
|
1719
|
+
model.trigger('error', model, resp, options);
|
1720
|
+
};
|
1721
|
+
};
|
1722
|
+
|
1723
|
+
return Backbone;
|
1724
|
+
|
1725
|
+
}));
|