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