diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000..f1b5b3c4 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,90 @@ +{ + "env": { + "browser": true, + "node": true, + "amd": true + }, + "globals": { + "attachEvent": false, + "detachEvent": false + }, + "rules": { + "array-bracket-spacing": 2, + "block-scoped-var": 2, + "brace-style": [1, "1tbs", {"allowSingleLine": true}], + "camelcase": 2, + "comma-dangle": [2, "never"], + "comma-spacing": 2, + "computed-property-spacing": [2, "never"], + "dot-notation": [2, { "allowKeywords": false }], + "eol-last": 2, + "eqeqeq": [2, "smart"], + "indent": [2, 2, {"SwitchCase": 1, "VariableDeclarator": 2}], + "key-spacing": 1, + "keyword-spacing": [2, { "after": true }], + "linebreak-style": 2, + "max-depth": [1, 4], + "max-params": [1, 5], + "new-cap": [2, {"newIsCapExceptions": ["model"]}], + "no-alert": 2, + "no-caller": 2, + "no-catch-shadow": 2, + "no-console": 2, + "no-debugger": 2, + "no-delete-var": 2, + "no-div-regex": 1, + "no-dupe-args": 2, + "no-dupe-keys": 2, + "no-duplicate-case": 2, + "no-else-return": 1, + "no-empty-character-class": 2, + "no-eval": 2, + "no-ex-assign": 2, + "no-extend-native": 2, + "no-extra-boolean-cast": 2, + "no-extra-parens": 1, + "no-extra-semi": 2, + "no-fallthrough": 2, + "no-floating-decimal": 2, + "no-func-assign": 2, + "no-implied-eval": 2, + "no-inner-declarations": 2, + "no-irregular-whitespace": 2, + "no-label-var": 2, + "no-labels": 2, + "no-lone-blocks": 2, + "no-lonely-if": 2, + "no-multi-str": 2, + "no-native-reassign": 2, + "no-negated-in-lhs": 1, + "no-new-object": 2, + "no-new-wrappers": 2, + "no-obj-calls": 2, + "no-octal": 2, + "no-octal-escape": 2, + "no-proto": 2, + "no-redeclare": 2, + "no-shadow": 2, + "no-spaced-func": 2, + "no-throw-literal": 2, + "no-trailing-spaces": 2, + "no-undef": 2, + "no-undef-init": 2, + "no-undefined": 2, + "no-unneeded-ternary": 2, + "no-unreachable": 2, + "no-unused-expressions": [2, {"allowTernary": true, "allowShortCircuit": true}], + "no-with": 2, + "object-curly-spacing": [2, "never"], + "quote-props": [1, "consistent-as-needed"], + "quotes": [2, "single", "avoid-escape"], + "radix": 2, + "semi": 2, + "space-before-function-paren": [2, {"anonymous": "never", "named": "never"}], + "space-infix-ops": 2, + "space-unary-ops": [2, { "words": true, "nonwords": false }], + "use-isnan": 2, + "valid-typeof": 2, + "wrap-iife": [2, "inside"] + } +} diff --git a/.travis.yml b/.travis.yml index 0da8ccf8..aa0cd87a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,14 +10,12 @@ before_script: - sh -e /etc/init.d/xvfb start script: - npm test - # Karma sauce is limited to running about 5-7 browsers (or it will timeout) at a time so we just run vendor by vendor here - - karma start karma.conf-sauce.js --browsers FIREFOX_V4,FIREFOX_V11,FIREFOX_V21,FIREFOX_V30,FIREFOX_V35,CHROME_V26,CHROME_V31,CHROME_V39,CHROME_V40,ANDROID_V4.0,ANDROID_V4.3 - - karma start karma.conf-sauce.js --browsers IE_V7,IE_V8,IE_V9,IE_V10,IE_V11 - - karma start karma.conf-sauce.js --browsers SAFARI_V5,SAFARI_V6,SAFARI_V7,SAFARI_V8.0,OPERA_V11,OPERA_V12 + - karma start karma.conf-sauce.js notifications: email: false sudo: false env: global: + - NPM_CONFIG_PROGRESS="false" - secure: G9oDQUXytNHni0wasGDXO3lQE/xuP9gd6VZ20kuh5FzVlqfY5L7JfYWki435nZ1z2yPD1QVAZi+1BCmCwnkTLVO9gB7cmDJDt1VzeHdCSOqCXGDAbOcq67/OO4FUa77sCQSDnqOOGVbiUPldaDl8G6uylk72Ll8b0pPwUWdRCM8= - secure: dniSzTSxXzaSGYjW3+LiNesx/BtTWo6RHuMKm19MwNo/YJYJJ/1YSEH/9vCmlVzc00CqvJ5Khwu9XPzcDV4gkuNQFN1+QcgGI2heVUqac/jqlGF39VEH8Xc+H40MsRLkwgSIkadIPWj4wBbbzqyC9M+J/KjUPOhBXGtp+FARu0I= diff --git a/LICENSE b/LICENSE index 184d1b99..51d7adcb 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2010-2015 Jeremy Ashkenas, DocumentCloud +Copyright (c) 2010-2017 Jeremy Ashkenas, DocumentCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation diff --git a/README.md b/README.md index 2f807762..276b7fc3 100644 --- a/README.md +++ b/README.md @@ -16,9 +16,14 @@ Backbone supplies structure to JavaScript-heavy applications by providing models For Docs, License, Tests, pre-packed downloads, and everything else, really, see: http://backbonejs.org -To suggest a feature, report a bug, or general discussion: +To suggest a feature or report a bug: https://github.com/jashkenas/backbone/issues +For questions on working with Backbone or general discussions: +https://groups.google.com/forum/#!forum/backbonejs, +http://stackoverflow.com/questions/tagged/backbone.js, or +https://gitter.im/jashkenas/backbone + Backbone is an open-sourced component of DocumentCloud: https://github.com/documentcloud diff --git a/backbone-min.js b/backbone-min.js index d2e95b43..435a72c9 100644 --- a/backbone-min.js +++ b/backbone-min.js @@ -1,2 +1,2 @@ -(function(t){var e=typeof self=="object"&&self.self==self&&self||typeof global=="object"&&global.global==global&&global;if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,s){e.Backbone=t(e,s,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore"),r;try{r=require("jquery")}catch(s){}t(e,exports,i,r)}else{e.Backbone=t(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}})(function(t,e,i,r){var s=t.Backbone;var n=[];var a=n.slice;e.VERSION="1.2.0";e.$=r;e.noConflict=function(){t.Backbone=s;return this};e.emulateHTTP=false;e.emulateJSON=false;var o=e.Events={};var h=/\s+/;var u=function(t,e,r,s,n){var a=0,o;if(r&&typeof r==="object"){for(o=i.keys(r);athis.length)n=this.length;if(n<0)n+=this.length+1;var s=[];var a=[];var h=[];var o=[];var l={};var u=e.add;var c=e.merge;var f=e.remove;var d=false;var v=this.comparator&&n==null&&e.sort!==false;var g=i.isString(this.comparator)?this.comparator:null;var p,m;for(m=0;m7);this._useHashChange=this._wantsHashChange&&this._hasHashChange;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.history&&this.history.pushState);this._usePushState=this._wantsPushState&&this._hasPushState;this.fragment=this.getFragment();this.root=("/"+this.root+"/").replace(O,"/");if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||"/";this.location.replace(e+"#"+this.getPath());return true}else if(this._hasPushState&&this.atRoot()){this.navigate(this.getHash(),{replace:true})}}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe");this.iframe.src="javascript:0";this.iframe.style.display="none";this.iframe.tabIndex=-1;var r=document.body;var n=r.insertBefore(this.iframe,r.firstChild).contentWindow;n.document.open();n.document.close();n.location.hash="#"+this.fragment}var s=window.addEventListener||function(t,e){return attachEvent("on"+t,e)};if(this._usePushState){s("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){s("hashchange",this.checkUrl,false)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}if(!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent("on"+t,e)};if(this._usePushState){t("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){t("hashchange",this.checkUrl,false)}if(this.iframe){document.body.removeChild(this.iframe);this.iframe=null}if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);N.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.getHash(this.iframe.contentWindow)}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){if(!this.matchRoot())return false;t=this.fragment=this.getFragment(t);return i.some(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!N.started)return false;if(!e||e===true)e={trigger:!!e};t=this.getFragment(t||"");var i=this.root;if(t===""||t.charAt(0)==="?"){i=i.slice(0,-1)||"/"}var r=i+t;t=this.decodeFragment(t.replace(U,""));if(this.fragment===t)return;this.fragment=t;if(this._usePushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,r)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var n=this.iframe.contentWindow;if(!e.replace){n.document.open();n.document.close()}this._updateHash(n.location,t,e.replace)}}else{return this.location.assign(r)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});e.history=new N;var q=function(t,e){var r=this;var n;if(t&&i.has(t,"constructor")){n=t.constructor}else{n=function(){return r.apply(this,arguments)}}i.extend(n,r,e);n.prototype=i.create(r.prototype,t);n.prototype.constructor=n;n.__super__=r.prototype;return n};y.extend=x.extend=$.extend=k.extend=N.extend=q;var F=function(){throw new Error('A "url" property or function must be specified')};var B=function(t,e){var i=e.error;e.error=function(r){if(i)i.call(e.context,t,r,e);t.trigger("error",t,r,e)}};return e}); //# sourceMappingURL=backbone-min.map \ No newline at end of file diff --git a/backbone-min.map b/backbone-min.map index 4b6d72da..0e1ce4e1 100644 --- a/backbone-min.map +++ b/backbone-min.map @@ -1 +1 @@ -{"version":3,"file":"backbone-min.js","sources":["backbone.js"],"names":["factory","root","self","global","define","amd","_","$","exports","Backbone","require","e","jQuery","Zepto","ender","previousBackbone","array","slice","VERSION","noConflict","this","emulateHTTP","emulateJSON","Events","eventSplitter","eventsApi","iteratee","memo","name","callback","opts","i","names","keys","length","test","split","on","context","internalOn","obj","listening","_events","onApi","ctx","listeners","_listeners","id","listenTo","_listenId","uniqueId","listeningTo","_listeningTo","thisId","objId","count","events","options","handlers","push","off","offApi","stopListening","ids","isEmpty","remaining","j","handler","_callback","size","once","onceMap","bind","listenToOnce","map","offer","apply","arguments","trigger","Math","max","args","Array","triggerApi","objEvents","cb","allEvents","all","triggerEvents","concat","ev","l","a1","a2","a3","call","addMethod","method","attribute","value","defaultVal","unshift","addUnderscoreMethods","Class","methods","each","prototype","unbind","extend","Model","attributes","attrs","cid","cidPrefix","collection","parse","defaults","result","set","changed","initialize","validationError","idAttribute","toJSON","clone","sync","get","attr","escape","has","matches","key","val","unset","changes","silent","changing","prev","current","_validate","_changing","_previousAttributes","isEqual","_pending","clear","hasChanged","changedAttributes","diff","old","previous","previousAttributes","fetch","model","success","resp","wrapError","save","xhr","wait","validate","serverAttrs","isObject","isNew","patch","destroy","defer","url","base","urlError","replace","encodeURIComponent","constructor","isValid","error","modelMethods","values","pairs","invert","pick","omit","chain","Collection","models","comparator","_reset","reset","setOptions","add","remove","merge","addOptions","singular","isArray","removed","_removeModels","existing","sort","at","sortable","sortAttr","isString","toAdd","toRemove","modelMap","order","orderChanged","_isModel","_prepareModel","_addReference","modelId","splice","orderedModels","addOpts","index","_removeReference","previousModels","pop","shift","_byId","where","first","findWhere","Error","sortBy","pluck","invoke","create","callbackOpts","indexOf","_onModelEvent","event","prevId","collectionMethods","forEach","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","some","any","include","contains","min","toArray","head","take","initial","rest","tail","drop","last","without","difference","shuffle","lastIndexOf","sample","partition","attributeMethods","iterator","isFunction","View","viewOptions","_ensureElement","delegateEventSplitter","tagName","selector","$el","render","_removeElement","setElement","element","undelegateEvents","_setElement","delegateEvents","el","match","delegate","eventName","listener","undelegate","_createElement","document","createElement","className","_setAttributes","type","methodMap","params","dataType","data","contentType","JSON","stringify","_method","beforeSend","setRequestHeader","processData","textStatus","errorThrown","ajax","update","delete","read","Router","routes","_bindRoutes","optionalParam","namedParam","splatParam","escapeRegExp","route","isRegExp","_routeToRegExp","router","history","fragment","_extractParameters","execute","navigate","optional","RegExp","exec","param","decodeURIComponent","History","bindAll","window","location","routeStripper","rootStripper","pathStripper","started","interval","atRoot","path","pathname","getSearch","matchRoot","decodeFragment","decodeURI","href","getHash","getPath","charAt","getFragment","_usePushState","_wantsHashChange","start","hashChange","_hasHashChange","_useHashChange","_wantsPushState","pushState","_hasPushState","iframe","src","style","display","tabIndex","body","insertBefore","firstChild","contentWindow","open","close","hash","addEventListener","attachEvent","checkUrl","_checkUrlInterval","setInterval","loadUrl","stop","removeEventListener","detachEvent","removeChild","frameElement","clearInterval","title","_updateHash","assign","protoProps","staticProps","parent","child","Surrogate","__super__"],"mappings":"CAOC,SAASA,GAIR,GAAIC,SAAeC,OAAQ,UAAYA,KAAKA,MAAQA,MAAQA,YAC1CC,SAAU,UAAYA,OAAOA,QAAUA,QAAUA,MAGnE,UAAWC,UAAW,YAAcA,OAAOC,IAAK,CAC9CD,QAAQ,aAAc,SAAU,WAAY,SAASE,EAAGC,EAAGC,GAGzDP,EAAKQ,SAAWT,EAAQC,EAAMO,EAASF,EAAGC,SAIvC,UAAWC,WAAY,YAAa,CACzC,GAAIF,GAAII,QAAQ,cAAeH,CAC/B,KAAMA,EAAIG,QAAQ,UAAa,MAAMC,IACrCX,EAAQC,EAAMO,QAASF,EAAGC,OAGrB,CACLN,EAAKQ,SAAWT,EAAQC,KAAUA,EAAKK,EAAIL,EAAKW,QAAUX,EAAKY,OAASZ,EAAKa,OAASb,EAAKM,MAG7F,SAASN,EAAMQ,EAAUH,EAAGC,GAO5B,GAAIQ,GAAmBd,EAAKQ,QAG5B,IAAIO,KACJ,IAAIC,GAAQD,EAAMC,KAGlBR,GAASS,QAAU,OAInBT,GAASF,EAAIA,CAIbE,GAASU,WAAa,WACpBlB,EAAKQ,SAAWM,CAChB,OAAOK,MAMTX,GAASY,YAAc,KAMvBZ,GAASa,YAAc,KAevB,IAAIC,GAASd,EAASc,SAGtB,IAAIC,GAAgB,KAOpB,IAAIC,GAAY,SAASC,EAAUC,EAAMC,EAAMC,EAAUC,GACvD,GAAIC,GAAI,EAAGC,CACX,IAAIJ,SAAeA,KAAS,SAAU,CAEpC,IAAKI,EAAQ1B,EAA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AAM1E,QAAQ,QAAS0E,EAAOE,EAAMjG,IAIxC,OAAOhD"} \ No newline at end of file +{"version":3,"sources":["backbone.js"],"names":["factory","root","self","global","define","amd","_","$","exports","Backbone","require","e","jQuery","Zepto","ender","previousBackbone","slice","Array","prototype","VERSION","noConflict","this","emulateHTTP","emulateJSON","addMethod","length","method","attribute","value","iteratee","context","cb","defaultVal","args","call","arguments","unshift","apply","addUnderscoreMethods","Class","methods","each","instance","isFunction","isObject","_isModel","modelMatcher","isString","model","get","attrs","matcher","matches","attributes","Events","eventSplitter","eventsApi","events","name","callback","opts","i","names","keys","test","split","on","internalOn","obj","listening","_events","onApi","ctx","listeners","_listeners","id","listenTo","_listenId","uniqueId","listeningTo","_listeningTo","thisId","objId","count","options","handlers","push","off","offApi","stopListening","ids","remaining","j","handler","_callback","once","onceMap","bind","listenToOnce","map","offer","trigger","Math","max","triggerApi","objEvents","allEvents","all","triggerEvents","concat","ev","l","a1","a2","a3","unbind","extend","Model","cid","cidPrefix","collection","parse","defaults","result","set","changed","initialize","validationError","idAttribute","toJSON","clone","sync","attr","escape","has","key","val","_validate","unset","silent","changes","changing","_changing","_previousAttributes","current","prev","isEqual","_pending","clear","hasChanged","isEmpty","changedAttributes","diff","old","size","previous","previousAttributes","fetch","success","resp","serverAttrs","wrapError","save","validate","wait","isNew","patch","xhr","destroy","defer","url","base","urlError","replace","encodeURIComponent","constructor","isValid","error","modelMethods","values","pairs","invert","pick","omit","chain","Collection","models","comparator","_reset","reset","setOptions","add","remove","merge","addOptions","splice","array","insert","at","min","tail","singular","isArray","removed","_removeModels","added","merged","toAdd","toMerge","toRemove","modelMap","sort","sortable","sortAttr","existing","_prepareModel","_addReference","orderChanged","some","m","index","_removeReference","previousModels","pop","shift","_byId","modelId","where","first","findWhere","Error","sortBy","pluck","create","callbackOpts","indexOf","_onModelEvent","event","prevId","collectionMethods","forEach","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","any","include","includes","contains","invoke","toArray","head","take","initial","rest","drop","last","without","difference","shuffle","lastIndexOf","sample","partition","groupBy","countBy","indexBy","findIndex","findLastIndex","View","viewOptions","_ensureElement","delegateEventSplitter","tagName","selector","$el","render","_removeElement","setElement","element","undelegateEvents","_setElement","delegateEvents","el","match","delegate","eventName","listener","undelegate","_createElement","document","createElement","className","_setAttributes","type","methodMap","params","dataType","data","contentType","JSON","stringify","_method","beforeSend","setRequestHeader","processData","textStatus","errorThrown","ajax","update","delete","read","Router","routes","_bindRoutes","optionalParam","namedParam","splatParam","escapeRegExp","route","isRegExp","_routeToRegExp","router","history","fragment","_extractParameters","execute","navigate","optional","RegExp","exec","param","decodeURIComponent","History","checkUrl","window","location","routeStripper","rootStripper","pathStripper","started","interval","atRoot","path","pathname","getSearch","matchRoot","decodeFragment","rootPath","decodeURI","href","getHash","getPath","charAt","getFragment","_usePushState","_wantsHashChange","start","hashChange","_hasHashChange","documentMode","_useHashChange","_wantsPushState","pushState","_hasPushState","iframe","src","style","display","tabIndex","body","iWindow","insertBefore","firstChild","contentWindow","open","close","hash","addEventListener","attachEvent","_checkUrlInterval","setInterval","loadUrl","stop","removeEventListener","detachEvent","removeChild","clearInterval","title","_updateHash","assign","protoProps","staticProps","parent","child","__super__"],"mappings":"CAOA,SAAUA,GAIR,GAAIC,SAAeC,OAAQ,UAAYA,KAAKA,OAASA,MAAQA,YAC3CC,SAAU,UAAYA,OAAOA,SAAWA,QAAUA,MAGpE,UAAWC,UAAW,YAAcA,OAAOC,IAAK,CAC9CD,QAAQ,aAAc,SAAU,WAAY,SAASE,EAAGC,EAAGC,GAGzDP,EAAKQ,SAAWT,EAAQC,EAAMO,EAASF,EAAGC,SAIvC,UAAWC,WAAY,YAAa,CACzC,GAAIF,GAAII,QAAQ,cAAeH,CAC/B,KAAMA,EAAIG,QAAQ,UAAa,MAAOC,IACtCX,EAAQC,EAAMO,QAASF,EAAGC,OAGrB,CACLN,EAAKQ,SAAWT,EAAQC,KAAUA,EAAKK,EAAIL,EAAKW,Q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AAKkD,EAAQtD,QAASkB,EAAO+G,EAAM3E,EACpDpC,GAAMqD,QAAQ,QAASrD,EAAO+G,EAAM3E,IAIxC,OAAO3E","file":"backbone-min.js"} \ No newline at end of file diff --git a/backbone.js b/backbone.js index 9e2e8eb7..a0fb826a 100644 --- a/backbone.js +++ b/backbone.js @@ -1,6 +1,6 @@ -// Backbone.js 1.2.0 +// Backbone.js 1.3.3 -// (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// (c) 2010-2017 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org @@ -9,8 +9,8 @@ // Establish the root object, `window` (`self`) in the browser, or `global` on the server. // We use `self` instead of `window` for `WebWorker` support. - var root = (typeof self == 'object' && self.self == self && self) || - (typeof global == 'object' && global.global == global && global); + var root = (typeof self == 'object' && self.self === self && self) || + (typeof global == 'object' && global.global === global && global); // Set up Backbone appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { @@ -23,7 +23,7 @@ // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'), $; - try { $ = require('jquery'); } catch(e) {} + try { $ = require('jquery'); } catch (e) {} factory(root, exports, _, $); // Finally, as a browser global. @@ -31,7 +31,7 @@ root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); } -}(function(root, Backbone, _, $) { +})(function(root, Backbone, _, $) { // Initial Setup // ------------- @@ -40,12 +40,11 @@ // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; - // Create local references to array methods we'll want to use later. - var array = []; - var slice = array.slice; + // Create a local reference to a common array method we'll want to use later. + var slice = Array.prototype.slice; // Current version of the library. Keep in sync with `package.json`. - Backbone.VERSION = '1.2.0'; + Backbone.VERSION = '1.3.3'; // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. @@ -69,12 +68,60 @@ // form param named `model`. Backbone.emulateJSON = false; + // Proxy Backbone class methods to Underscore functions, wrapping the model's + // `attributes` object or collection's `models` array behind the scenes. + // + // collection.filter(function(model) { return model.get('age') > 10 }); + // collection.each(this.addView); + // + // `Function#apply` can be slow so we use the method's arg count, if we know it. + var addMethod = function(length, method, attribute) { + switch (length) { + case 1: return function() { + return _[method](this[attribute]); + }; + case 2: return function(value) { + return _[method](this[attribute], value); + }; + case 3: return function(iteratee, context) { + return _[method](this[attribute], cb(iteratee, this), context); + }; + case 4: return function(iteratee, defaultVal, context) { + return _[method](this[attribute], cb(iteratee, this), defaultVal, context); + }; + default: return function() { + var args = slice.call(arguments); + args.unshift(this[attribute]); + return _[method].apply(_, args); + }; + } + }; + var addUnderscoreMethods = function(Class, methods, attribute) { + _.each(methods, function(length, method) { + if (_[method]) Class.prototype[method] = addMethod(length, method, attribute); + }); + }; + + // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`. + var cb = function(iteratee, instance) { + if (_.isFunction(iteratee)) return iteratee; + if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee); + if (_.isString(iteratee)) return function(model) { return model.get(iteratee); }; + return iteratee; + }; + var modelMatcher = function(attrs) { + var matcher = _.matches(attrs); + return function(model) { + return matcher(model.attributes); + }; + }; + // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with - // custom events. You may bind with `on` or remove with `off` callback - // functions to an event; `trigger`-ing an event fires all callbacks in + // a custom event channel. You may bind a callback to an event with `on` or + // remove with `off`; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; @@ -92,25 +139,25 @@ // Iterates over the standard `event, callback` (as well as the fancy multiple // space-separated events `"change blur", callback` and jQuery-style event - // maps `{event: callback}`), reducing them by manipulating `memo`. - // Passes a normalized single event name and callback, as well as any - // optional `opts`. - var eventsApi = function(iteratee, memo, name, callback, opts) { + // maps `{event: callback}`). + var eventsApi = function(iteratee, events, name, callback, opts) { var i = 0, names; if (name && typeof name === 'object') { // Handle event maps. - for (names = _.keys(name); i < names.length; i++) { - memo = iteratee(memo, names[i], name[names[i]], opts); + if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback; + for (names = _.keys(name); i < names.length ; i++) { + events = eventsApi(iteratee, events, names[i], name[names[i]], opts); } } else if (name && eventSplitter.test(name)) { - // Handle space separated event names. + // Handle space-separated event names by delegating them individually. for (names = name.split(eventSplitter); i < names.length; i++) { - memo = iteratee(memo, names[i], callback, opts); + events = iteratee(events, names[i], callback, opts); } } else { - memo = iteratee(memo, name, callback, opts); + // Finally, standard events. + events = iteratee(events, name, callback, opts); } - return memo; + return events; }; // Bind an event to a `callback` function. Passing `"all"` will bind @@ -134,7 +181,8 @@ }; // Inversion-of-control versions of `on`. Tell *this* object to listen to - // an event in another object... keeping track of what it's listening to. + // an event in another object... keeping track of what it's listening to + // for easier unbinding later. Events.listenTo = function(obj, name, callback) { if (!obj) return this; var id = obj._listenId || (obj._listenId = _.uniqueId('l')); @@ -166,7 +214,7 @@ var context = options.context, ctx = options.ctx, listening = options.listening; if (listening) listening.count++; - handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening }); + handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening}); } return events; }; @@ -185,7 +233,7 @@ // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. - Events.off = function(name, callback, context) { + Events.off = function(name, callback, context) { if (!this._events) return this; this._events = eventsApi(offApi, this._events, name, callback, { context: context, @@ -197,7 +245,7 @@ // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. - Events.stopListening = function(obj, name, callback) { + Events.stopListening = function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; @@ -212,12 +260,13 @@ listening.obj.off(name, callback, this); if (listening.interop) listening.off(name, callback); } + if (_.isEmpty(listeningTo)) this._listeningTo = void 0; + return this; }; // The reducing API that removes a callback from the `events` object. var offApi = function(events, name, callback, options) { - // No events to consider. if (!events) return; var context = options.context, listeners = options.listeners; @@ -231,7 +280,7 @@ return; } - var names = name ? [name] : _.keys(events); + names = name ? [name] : _.keys(events); for (; i < names.length; i++) { name = names[i]; var handlers = events[name]; @@ -263,28 +312,29 @@ } } - if (_.size(events)) return events; + return events; }; // Bind an event to only be triggered a single time. After the first time - // the callback is invoked, it will be removed. When multiple events are - // passed in using the space-separated syntax, the event will fire once for every - // event you passed in, not once for a combination of all events - Events.once = function(name, callback, context) { + // the callback is invoked, its listener will be removed. If multiple events + // are passed in using the space-separated syntax, the handler will fire + // once for each event, not once for a combination of all events. + Events.once = function(name, callback, context) { // Map the event into a `{event: once}` object. var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this)); - return this.on(events, void 0, context); + if (typeof name === 'string' && context == null) callback = void 0; + return this.on(events, callback, context); }; // Inversion-of-control versions of `once`. - Events.listenToOnce = function(obj, name, callback) { + Events.listenToOnce = function(obj, name, callback) { // Map the event into a `{event: once}` object. var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj)); return this.listenTo(obj, events); }; // Reduces the event callbacks into a map of `{event: onceWrapper}`. - // `offer` unbinds the `onceWrapper` after it as been called. + // `offer` unbinds the `onceWrapper` after it has been called. var onceMap = function(map, name, callback, offer) { if (callback) { var once = map[name] = _.once(function() { @@ -300,7 +350,7 @@ // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). - Events.trigger = function(name) { + Events.trigger = function(name) { if (!this._events) return this; var length = Math.max(0, arguments.length - 1); @@ -312,7 +362,7 @@ }; // Handles triggering the appropriate event callbacks. - var triggerApi = function(objEvents, name, cb, args) { + var triggerApi = function(objEvents, name, callback, args) { if (objEvents) { var events = objEvents[name]; var allEvents = objEvents.all; @@ -375,35 +425,6 @@ if (!this.interop) delete this.obj._listeners[this.id]; }; - // Proxy Underscore methods to a Backbone class' prototype using a - // particular attribute as the data argument - var addMethod = function(length, method, attribute) { - switch (length) { - case 1: return function() { - return _[method](this[attribute]); - }; - case 2: return function(value) { - return _[method](this[attribute], value); - }; - case 3: return function(iteratee, context) { - return _[method](this[attribute], iteratee, context); - }; - case 4: return function(iteratee, defaultVal, context) { - return _[method](this[attribute], iteratee, defaultVal, context); - }; - default: return function() { - var args = slice.call(arguments); - args.unshift(this[attribute]); - return _[method].apply(_, args); - }; - } - }; - var addUnderscoreMethods = function(Class, methods, attribute) { - _.each(methods, function(length, method) { - if (_[method]) Class.prototype[method] = addMethod(length, method, attribute); - }); - }; - // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; @@ -425,11 +446,13 @@ var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); + this.preinitialize.apply(this, arguments); this.cid = _.uniqueId(this.cidPrefix); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; - attrs = _.defaults({}, attrs, _.result(this, 'defaults')); + var defaults = _.result(this, 'defaults'); + attrs = _.defaults(_.extend({}, defaults, attrs), defaults); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); @@ -452,6 +475,10 @@ // You may want to override this if you're experiencing name clashes with model ids. cidPrefix: 'c', + // preinitialize is an empty function by default. You can override it with a function + // or object. preinitialize will run before any instantiation logic is run in the Model. + preinitialize: function(){}, + // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, @@ -492,10 +519,10 @@ // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { - var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. + var attrs; if (typeof key === 'object') { attrs = key; options = val; @@ -509,33 +536,36 @@ if (!this._validate(attrs, options)) return false; // Extract attributes and options. - unset = options.unset; - silent = options.silent; - changes = []; - changing = this._changing; - this._changing = true; + var unset = options.unset; + var silent = options.silent; + var changes = []; + var changing = this._changing; + this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } - current = this.attributes, prev = this._previousAttributes; - // Check for changes of `id`. - if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + var current = this.attributes; + var changed = this.changed; + var prev = this._previousAttributes; // For each `set` attribute, update or delete the current value. - for (attr in attrs) { + for (var attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { - this.changed[attr] = val; + changed[attr] = val; } else { - delete this.changed[attr]; + delete changed[attr]; } unset ? delete current[attr] : current[attr] = val; } + // Update the `id`. + if (this.idAttribute in attrs) this.id = this.get(this.idAttribute); + // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = options; @@ -587,13 +617,16 @@ // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; - var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; + var changed = {}; + var hasChanged; for (var attr in diff) { - if (_.isEqual(old[attr], (val = diff[attr]))) continue; - (changed || (changed = {}))[attr] = val; + var val = diff[attr]; + if (_.isEqual(old[attr], val)) continue; + changed[attr] = val; + hasChanged = true; } - return changed; + return hasChanged ? changed : false; }, // Get the previous value of an attribute, recorded at the time the last @@ -612,12 +645,12 @@ // Fetch the model from the server, merging the response with the model's // local attributes. Any changed attributes will trigger a "change" event. fetch: function(options) { - options = options ? _.clone(options) : {}; - if (options.parse === void 0) options.parse = true; + options = _.extend({parse: true}, options); var model = this; var success = options.success; options.success = function(resp) { - if (!model.set(model.parse(resp, options), options)) return false; + var serverAttrs = options.parse ? model.parse(resp, options) : resp; + if (!model.set(serverAttrs, options)) return false; if (success) success.call(options.context, model, resp, options); model.trigger('sync', model, resp, options); }; @@ -629,9 +662,8 @@ // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { - var attrs, method, xhr, attributes = this.attributes, wait; - // Handle both `"key", value` and `{key: value}` -style arguments. + var attrs; if (key == null || typeof key === 'object') { attrs = key; options = val; @@ -639,47 +671,43 @@ (attrs = {})[key] = val; } - options = _.extend({validate: true}, options); - wait = options.wait; + options = _.extend({validate: true, parse: true}, options); + var wait = options.wait; // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !wait) { if (!this.set(attrs, options)) return false; - } else { - if (!this._validate(attrs, options)) return false; - } - - // Set temporary attributes if `{wait: true}`. - if (attrs && wait) { - this.attributes = _.extend({}, attributes, attrs); + } else if (!this._validate(attrs, options)) { + return false; } // After a successful server-side save, the client is (optionally) // updated with the server-side state. - if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; + var attributes = this.attributes; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = options.parse ? model.parse(resp, options) : resp; - if (wait) serverAttrs = _.extend(attrs || {}, serverAttrs); - if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { - return false; - } + if (wait) serverAttrs = _.extend({}, attrs, serverAttrs); + if (serverAttrs && !model.set(serverAttrs, options)) return false; if (success) success.call(options.context, model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); - method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); + // Set temporary attributes if `{wait: true}` to properly find new ids. + if (attrs && wait) this.attributes = _.extend({}, attributes, attrs); + + var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch' && !options.attrs) options.attrs = attrs; - xhr = this.sync(method, this, options); + var xhr = this.sync(method, this, options); // Restore attributes. - if (attrs && wait) this.attributes = attributes; + this.attributes = attributes; return xhr; }, @@ -724,8 +752,8 @@ _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; - var id = this.id || this.attributes[this.idAttribute]; - return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(id); + var id = this.get(this.idAttribute); + return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); }, // **parse** converts a response into the hash of attributes to be `set` on @@ -746,7 +774,7 @@ // Check if the model is currently in a valid state. isValid: function(options) { - return this._validate({}, _.extend(options || {}, { validate: true })); + return this._validate({}, _.extend({}, options, {validate: true})); }, // Run validation against the next complete set of model attributes, @@ -762,9 +790,10 @@ }); - // Underscore methods that we want to implement on the Model. - var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0, - omit: 0, chain: 1, isEmpty: 1 }; + // Underscore methods that we want to implement on the Model, mapped to the + // number of arguments they take. + var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0, + omit: 0, chain: 1, isEmpty: 1}; // Mix in each Underscore method as a proxy to `Model#attributes`. addUnderscoreMethods(Model, modelMethods, 'attributes'); @@ -784,6 +813,7 @@ // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); + this.preinitialize.apply(this, arguments); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); @@ -795,6 +825,17 @@ var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; + // Splices `insert` into `array` at index `at`. + var splice = function(array, insert, at) { + at = Math.min(Math.max(at, 0), array.length); + var tail = Array(array.length - at); + var length = insert.length; + var i; + for (i = 0; i < tail.length; i++) tail[i] = array[i + at]; + for (i = 0; i < length; i++) array[i + at] = insert[i]; + for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i]; + }; + // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { @@ -802,6 +843,11 @@ // This should be overridden in most cases. model: Model, + + // preinitialize is an empty function by default. You can override it with a function + // or object. preinitialize will run before any instantiation logic is run in the Collection. + preinitialize: function(){}, + // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, @@ -809,7 +855,7 @@ // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { - return this.map(function(model){ return model.toJSON(options); }); + return this.map(function(model) { return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. @@ -817,19 +863,24 @@ return Backbone.sync.apply(this, arguments); }, - // Add a model, or list of models to the set. + // Add a model, or list of models to the set. `models` may be Backbone + // Models or raw JavaScript objects to be converted to Models, or any + // combination of the two. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { - var singular = !_.isArray(models), removed; - models = singular ? [models] : _.clone(models); - options || (options = {}); - removed = this._removeModels(models, options); - if (!options.silent && removed) this.trigger('update', this, options); - return singular ? models[0] : models; + options = _.extend({}, options); + var singular = !_.isArray(models); + models = singular ? [models] : models.slice(); + var removed = this._removeModels(models, options); + if (!options.silent && removed.length) { + options.changes = {added: [], merged: [], removed: removed}; + this.trigger('update', this, options); + } + return singular ? removed[0] : removed; }, // Update a collection by `set`-ing a new list of models, adding new ones, @@ -837,97 +888,114 @@ // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { - options = _.defaults({}, options, setOptions); - if (options.parse) models = this.parse(models, options); + if (models == null) return; + + options = _.extend({}, setOptions, options); + if (options.parse && !this._isModel(models)) { + models = this.parse(models, options) || []; + } + var singular = !_.isArray(models); - models = singular ? (models ? [models] : []) : models.slice(); - var id, model, attrs, existing, sort; + models = singular ? [models] : models.slice(); + var at = options.at; if (at != null) at = +at; + if (at > this.length) at = this.length; if (at < 0) at += this.length + 1; - var sortable = this.comparator && (at == null) && options.sort !== false; + + var set = []; + var toAdd = []; + var toMerge = []; + var toRemove = []; + var modelMap = {}; + + var add = options.add; + var merge = options.merge; + var remove = options.remove; + + var sort = false; + var sortable = this.comparator && at == null && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; - var toAdd = [], toRemove = [], modelMap = {}; - var add = options.add, merge = options.merge, remove = options.remove; - var order = !sortable && add && remove ? [] : false; - var orderChanged = false; // Turn bare objects into model references, and prevent invalid models // from being added. - for (var i = 0; i < models.length; i++) { - attrs = models[i]; + var model, i; + for (i = 0; i < models.length; i++) { + model = models[i]; // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. - if (existing = this.get(attrs)) { - if (remove) modelMap[existing.cid] = true; - if (merge && attrs !== existing) { - attrs = this._isModel(attrs) ? attrs.attributes : attrs; + var existing = this.get(model); + if (existing) { + if (merge && model !== existing) { + var attrs = this._isModel(model) ? model.attributes : model; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); - if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; + toMerge.push(existing); + if (sortable && !sort) sort = existing.hasChanged(sortAttr); + } + if (!modelMap[existing.cid]) { + modelMap[existing.cid] = true; + set.push(existing); } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { - model = models[i] = this._prepareModel(attrs, options); - if (!model) continue; - toAdd.push(model); - this._addReference(model, options); + model = models[i] = this._prepareModel(model, options); + if (model) { + toAdd.push(model); + this._addReference(model, options); + modelMap[model.cid] = true; + set.push(model); + } } - - // Do not add multiple models with the same `id`. - model = existing || model; - if (!model) continue; - id = this.modelId(model.attributes); - if (order && (model.isNew() || !modelMap[id])) { - order.push(model); - - // Check to see if this is actually a new model at this index. - orderChanged = orderChanged || !this.models[i] || model.cid !== this.models[i].cid; - } - - modelMap[id] = true; } - // Remove nonexistent models if appropriate. + // Remove stale models. if (remove) { - for (var i = 0; i < this.length; i++) { - if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); + for (i = 0; i < this.length; i++) { + model = this.models[i]; + if (!modelMap[model.cid]) toRemove.push(model); } if (toRemove.length) this._removeModels(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. - if (toAdd.length || orderChanged) { + var orderChanged = false; + var replace = !sortable && add && remove; + if (set.length && replace) { + orderChanged = this.length !== set.length || _.some(this.models, function(m, index) { + return m !== set[index]; + }); + this.models.length = 0; + splice(this.models, set, 0); + this.length = this.models.length; + } else if (toAdd.length) { if (sortable) sort = true; - this.length += toAdd.length; - if (at != null) { - for (var i = 0; i < toAdd.length; i++) { - this.models.splice(at + i, 0, toAdd[i]); - } - } else { - if (order) this.models.length = 0; - var orderedModels = order || toAdd; - for (var i = 0; i < orderedModels.length; i++) { - this.models.push(orderedModels[i]); - } - } + splice(this.models, toAdd, at == null ? this.length : at); + this.length = this.models.length; } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); - // Unless silenced, it's time to fire all appropriate add/sort events. + // Unless silenced, it's time to fire all appropriate add/sort/update events. if (!options.silent) { - var addOpts = at != null ? _.clone(options) : options; - for (var i = 0; i < toAdd.length; i++) { - if (at != null) addOpts.index = at + i; - (model = toAdd[i]).trigger('add', model, this, addOpts); + for (i = 0; i < toAdd.length; i++) { + if (at != null) options.index = at + i; + model = toAdd[i]; + model.trigger('add', model, this, options); } if (sort || orderChanged) this.trigger('sort', this, options); - if (toAdd.length || toRemove.length) this.trigger('update', this, options); + if (toAdd.length || toRemove.length || toMerge.length) { + options.changes = { + added: toAdd, + removed: toRemove, + merged: toMerge + }; + this.trigger('update', this, options); + } } // Return the added (or merged) model (or models). @@ -958,8 +1026,7 @@ // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); - this.remove(model, options); - return model; + return this.remove(model, options); }, // Add a model to the beginning of the collection. @@ -970,8 +1037,7 @@ // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); - this.remove(model, options); - return model; + return this.remove(model, options); }, // Slice out a sub-array of models from the collection. @@ -979,11 +1045,18 @@ return slice.apply(this.models, arguments); }, - // Get a model from the set by id. + // Get a model from the set by id, cid, model object with id or cid + // properties, or an attributes object that is transformed through modelId. get: function(obj) { if (obj == null) return void 0; - var id = this.modelId(this._isModel(obj) ? obj.attributes : obj); - return this._byId[obj] || this._byId[id] || this._byId[obj.cid]; + return this._byId[obj] || + this._byId[this.modelId(this._isModel(obj) ? obj.attributes : obj)] || + obj.cid && this._byId[obj.cid]; + }, + + // Returns `true` if the model is in the collection. + has: function(obj) { + return this.get(obj) != null; }, // Get the model at the given index. @@ -995,10 +1068,7 @@ // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { - var matches = _.matches(attrs); - return this[first ? 'find' : 'filter'](function(model) { - return matches(model.attributes); - }); + return this[first ? 'find' : 'filter'](attrs); }, // Return the first model with matching attributes. Useful for simple cases @@ -1011,31 +1081,33 @@ // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { - if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); + var comparator = this.comparator; + if (!comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); - // Run sort based on type of `comparator`. - if (_.isString(this.comparator) || this.comparator.length === 1) { - this.models = this.sortBy(this.comparator, this); - } else { - this.models.sort(_.bind(this.comparator, this)); - } + var length = comparator.length; + if (_.isFunction(comparator)) comparator = _.bind(comparator, this); + // Run sort based on type of `comparator`. + if (length === 1 || _.isString(comparator)) { + this.models = this.sortBy(comparator); + } else { + this.models.sort(comparator); + } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { - return _.invoke(this.models, 'get', attr); + return this.map(attr + ''); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { - options = options ? _.clone(options) : {}; - if (options.parse === void 0) options.parse = true; + options = _.extend({parse: true}, options); var success = options.success; var collection = this; options.success = function(resp) { @@ -1054,13 +1126,14 @@ create: function(model, options) { options = options ? _.clone(options) : {}; var wait = options.wait; - if (!(model = this._prepareModel(model, options))) return false; + model = this._prepareModel(model, options); + if (!model) return false; if (!wait) this.add(model, options); var collection = this; var success = options.success; - options.success = function(model, resp, callbackOpts) { - if (wait) collection.add(model, callbackOpts); - if (success) success.call(callbackOpts.context, model, resp, callbackOpts); + options.success = function(m, resp, callbackOpts) { + if (wait) collection.add(m, callbackOpts); + if (success) success.call(callbackOpts.context, m, resp, callbackOpts); }; model.save(null, options); return model; @@ -1081,10 +1154,25 @@ }, // Define how to uniquely identify models in the collection. - modelId: function (attrs) { + modelId: function(attrs) { return attrs[this.model.prototype.idAttribute || 'id']; }, + // Get an iterator of all models in this collection. + values: function() { + return new CollectionIterator(this, ITERATOR_VALUES); + }, + + // Get an iterator of all model IDs in this collection. + keys: function() { + return new CollectionIterator(this, ITERATOR_KEYS); + }, + + // Get an iterator of all [ID, model] tuples in this collection. + entries: function() { + return new CollectionIterator(this, ITERATOR_KEYSVALUES); + }, + // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { @@ -1108,36 +1196,37 @@ return false; }, - // Internal method called by both remove and set. Does not trigger any - // additional events. Returns true if anything was actually removed. + // Internal method called by both remove and set. _removeModels: function(models, options) { - var i, l, index, model, removed = false; - for (var i = 0, j = 0; i < models.length; i++) { - var model = models[i] = this.get(models[i]); + var removed = []; + for (var i = 0; i < models.length; i++) { + var model = this.get(models[i]); if (!model) continue; - var id = this.modelId(model.attributes); - if (id != null) delete this._byId[id]; - delete this._byId[model.cid]; + var index = this.indexOf(model); this.models.splice(index, 1); this.length--; + + // Remove references before triggering 'remove' event to prevent an + // infinite loop. #3693 + delete this._byId[model.cid]; + var id = this.modelId(model.attributes); + if (id != null) delete this._byId[id]; + if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } - models[j++] = model; + + removed.push(model); this._removeReference(model, options); - removed = true; } - // We only need to slice if models array should be smaller, which is - // caused by some models not actually getting removed. - if (models.length !== j) models = models.slice(0, j); return removed; }, // Method for checking whether an object should be considered a model for // the purposes of adding to the collection. - _isModel: function (model) { + _isModel: function(model) { return model instanceof Model; }, @@ -1151,6 +1240,9 @@ // Internal method to sever a model's ties to a collection. _removeReference: function(model, options) { + delete this._byId[model.cid]; + var id = this.modelId(model.attributes); + if (id != null) delete this._byId[id]; if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, @@ -1160,14 +1252,16 @@ // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { - if ((event === 'add' || event === 'remove') && collection !== this) return; - if (event === 'destroy') this.remove(model, options); - if (event === 'change') { - var prevId = this.modelId(model.previousAttributes()); - var id = this.modelId(model.attributes); - if (prevId !== id) { - if (prevId != null) delete this._byId[prevId]; - if (id != null) this._byId[id] = model; + if (model) { + if ((event === 'add' || event === 'remove') && collection !== this) return; + if (event === 'destroy') this.remove(model, options); + if (event === 'change') { + var prevId = this.modelId(model.previousAttributes()); + var id = this.modelId(model.attributes); + if (prevId !== id) { + if (prevId != null) delete this._byId[prevId]; + if (id != null) this._byId[id] = model; + } } } this.trigger.apply(this, arguments); @@ -1175,34 +1269,87 @@ }); + // Defining an @@iterator method implements JavaScript's Iterable protocol. + // In modern ES2015 browsers, this value is found at Symbol.iterator. + /* global Symbol */ + var $$iterator = typeof Symbol === 'function' && Symbol.iterator; + if ($$iterator) { + Collection.prototype[$$iterator] = Collection.prototype.values; + } + + // CollectionIterator + // ------------------ + + // A CollectionIterator implements JavaScript's Iterator protocol, allowing the + // use of `for of` loops in modern browsers and interoperation between + // Backbone.Collection and other JavaScript functions and third-party libraries + // which can operate on Iterables. + var CollectionIterator = function(collection, kind) { + this._collection = collection; + this._kind = kind; + this._index = 0; + }; + + // This "enum" defines the three possible kinds of values which can be emitted + // by a CollectionIterator that correspond to the values(), keys() and entries() + // methods on Collection, respectively. + var ITERATOR_VALUES = 1; + var ITERATOR_KEYS = 2; + var ITERATOR_KEYSVALUES = 3; + + // All Iterators should themselves be Iterable. + if ($$iterator) { + CollectionIterator.prototype[$$iterator] = function() { + return this; + }; + } + + CollectionIterator.prototype.next = function() { + if (this._collection) { + + // Only continue iterating if the iterated collection is long enough. + if (this._index < this._collection.length) { + var model = this._collection.at(this._index); + this._index++; + + // Construct a value depending on what kind of values should be iterated. + var value; + if (this._kind === ITERATOR_VALUES) { + value = model; + } else { + var id = this._collection.modelId(model.attributes); + if (this._kind === ITERATOR_KEYS) { + value = id; + } else { // ITERATOR_KEYSVALUES + value = [id, model]; + } + } + return {value: value, done: false}; + } + + // Once exhausted, remove the reference to the collection so future + // calls to the next method always return done. + this._collection = void 0; + } + + return {value: void 0, done: true}; + }; + // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: - var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4, - foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3, - select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 2, - contains: 2, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, + var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0, + foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3, + select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3, + contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3, without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3, - isEmpty: 1, chain: 1, sample: 3, partition: 3 }; + isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3, + sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3}; // Mix in each Underscore method as a proxy to `Collection#models`. addUnderscoreMethods(Collection, collectionMethods, 'models'); - // Underscore methods that take a property name as an argument. - var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; - - // Use attributes instead of properties. - _.each(attributeMethods, function(method) { - if (!_[method]) return; - Collection.prototype[method] = function(value, context) { - var iterator = _.isFunction(value) ? value : function(model) { - return model.get(value); - }; - return _[method](this.models, iterator, context); - }; - }); - // Backbone.View // ------------- @@ -1218,7 +1365,7 @@ // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); - options || (options = {}); + this.preinitialize.apply(this, arguments); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); @@ -1227,7 +1374,7 @@ // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; - // List of view options to be merged as properties. + // List of view options to be set as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. @@ -1242,6 +1389,10 @@ return this.$el.find(selector); }, + // preinitialize is an empty function by default. You can override it with a function + // or object. preinitialize will run before any instantiation logic is run in the View + preinitialize: function(){}, + // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, @@ -1301,11 +1452,12 @@ // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. delegateEvents: function(events) { - if (!(events || (events = _.result(this, 'events')))) return this; + events || (events = _.result(this, 'events')); + if (!events) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; - if (!_.isFunction(method)) method = this[events[key]]; + if (!_.isFunction(method)) method = this[method]; if (!method) continue; var match = key.match(delegateEventSplitter); this.delegate(match[1], match[2], _.bind(method, this)); @@ -1318,6 +1470,7 @@ // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer. delegate: function(eventName, selector, listener) { this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener); + return this; }, // Clears all callbacks previously bound to the view by `delegateEvents`. @@ -1332,6 +1485,7 @@ // `selector` and `listener` are both optional. undelegate: function(eventName, selector, listener) { this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener); + return this; }, // Produces a DOM element to be assigned to your view. Exposed for @@ -1446,9 +1600,9 @@ var methodMap = { 'create': 'POST', 'update': 'PUT', - 'patch': 'PATCH', + 'patch': 'PATCH', 'delete': 'DELETE', - 'read': 'GET' + 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. @@ -1464,6 +1618,7 @@ // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); + this.preinitialize.apply(this, arguments); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); @@ -1479,6 +1634,10 @@ // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { + // preinitialize is an empty function by default. You can override it with a function + // or object. preinitialize will run before any instantiation logic is run in the Router. + preinitialize: function(){}, + // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, @@ -1568,7 +1727,7 @@ // falls back to polling. var History = Backbone.History = function() { this.handlers = []; - _.bindAll(this, 'checkUrl'); + this.checkUrl = _.bind(this.checkUrl, this); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { @@ -1605,8 +1764,8 @@ // Does the pathname match the root? matchRoot: function() { var path = this.decodeFragment(this.location.pathname); - var root = path.slice(0, this.root.length - 1) + '/'; - return root === this.root; + var rootPath = path.slice(0, this.root.length - 1) + '/'; + return rootPath === this.root; }, // Unicode characters in `location.pathname` are percent encoded so they're @@ -1661,7 +1820,7 @@ this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; - this._hasHashChange = 'onhashchange' in window; + this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); this._useHashChange = this._wantsHashChange && this._hasHashChange; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.history && this.history.pushState); @@ -1678,8 +1837,8 @@ // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { - var root = this.root.slice(0, -1) || '/'; - this.location.replace(root + '#' + this.getPath()); + var rootPath = this.root.slice(0, -1) || '/'; + this.location.replace(rootPath + '#' + this.getPath()); // Return immediately as browser will do redirect to new url return true; @@ -1695,19 +1854,20 @@ // support the `hashchange` event, HTML5 history, or the user wants // `hashChange` but not `pushState`. if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) { - var iframe = document.createElement('iframe'); - iframe.src = 'javascript:0'; - iframe.style.display = 'none'; - iframe.tabIndex = -1; + this.iframe = document.createElement('iframe'); + this.iframe.src = 'javascript:0'; + this.iframe.style.display = 'none'; + this.iframe.tabIndex = -1; var body = document.body; // Using `appendChild` will throw on IE < 9 if the document is not ready. - this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow; - this.iframe.document.open().close(); - this.iframe.location.hash = '#' + this.fragment; + var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow; + iWindow.document.open(); + iWindow.document.close(); + iWindow.location.hash = '#' + this.fragment; } // Add a cross-platform `addEventListener` shim for older browsers. - var addEventListener = window.addEventListener || function (eventName, listener) { + var addEventListener = window.addEventListener || function(eventName, listener) { return attachEvent('on' + eventName, listener); }; @@ -1728,7 +1888,7 @@ // but possibly useful for unit testing Routers. stop: function() { // Add a cross-platform `removeEventListener` shim for older browsers. - var removeEventListener = window.removeEventListener || function (eventName, listener) { + var removeEventListener = window.removeEventListener || function(eventName, listener) { return detachEvent('on' + eventName, listener); }; @@ -1741,7 +1901,7 @@ // Clean up the iframe if necessary. if (this.iframe) { - document.body.removeChild(this.iframe.frameElement); + document.body.removeChild(this.iframe); this.iframe = null; } @@ -1764,7 +1924,7 @@ // If the user pressed the back button, the iframe's hash will have // changed and we should use that for comparison. if (current === this.fragment && this.iframe) { - current = this.getHash(this.iframe); + current = this.getHash(this.iframe.contentWindow); } if (current === this.fragment) return false; @@ -1779,7 +1939,7 @@ // If the root doesn't match, no routes can match either. if (!this.matchRoot()) return false; fragment = this.fragment = this.getFragment(fragment); - return _.any(this.handlers, function(handler) { + return _.some(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; @@ -1802,17 +1962,20 @@ fragment = this.getFragment(fragment || ''); // Don't include a trailing slash on the root. - var root = this.root; + var rootPath = this.root; if (fragment === '' || fragment.charAt(0) === '?') { - root = root.slice(0, -1) || '/'; + rootPath = rootPath.slice(0, -1) || '/'; } - var url = root + fragment; + var url = rootPath + fragment; - // Strip the hash and decode for matching. - fragment = this.decodeFragment(fragment.replace(pathStripper, '')); + // Strip the fragment of the query and hash for matching. + fragment = fragment.replace(pathStripper, ''); - if (this.fragment === fragment) return; - this.fragment = fragment; + // Decode for matching. + var decodedFragment = this.decodeFragment(fragment); + + if (this.fragment === decodedFragment) return; + this.fragment = decodedFragment; // If pushState is available, we use it to set the fragment as a real URL. if (this._usePushState) { @@ -1822,12 +1985,18 @@ // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); - if (this.iframe && (fragment !== this.getHash(this.iframe))) { + if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) { + var iWindow = this.iframe.contentWindow; + // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. - if (!options.replace) this.iframe.document.open().close(); - this._updateHash(this.iframe.location, fragment, options.replace); + if (!options.replace) { + iWindow.document.open(); + iWindow.document.close(); + } + + this._updateHash(iWindow.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- @@ -1878,14 +2047,9 @@ _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling - // `parent` constructor function. - var Surrogate = function(){ this.constructor = child; }; - Surrogate.prototype = parent.prototype; - child.prototype = new Surrogate; - - // Add prototype properties (instance properties) to the subclass, - // if supplied. - if (protoProps) _.extend(child.prototype, protoProps); + // `parent`'s constructor function and add the prototype properties. + child.prototype = _.create(parent.prototype, protoProps); + child.prototype.constructor = child; // Set a convenience property in case the parent's prototype is needed // later. @@ -1912,5 +2076,4 @@ }; return Backbone; - -})); +}); diff --git a/bower.json b/bower.json index 81c04e12..89e68869 100644 --- a/bower.json +++ b/bower.json @@ -1,9 +1,8 @@ { "name" : "backbone", - "version" : "1.2.0", "main" : "backbone.js", "dependencies" : { - "underscore" : ">=1.7.0" + "underscore" : ">=1.8.3" }, - "ignore" : ["docs", "examples", "test", "*.yml", "*.html", "*.ico", "*.md", "CNAME", ".*", "karma.*", "component.json", "package.json"] + "ignore" : ["docs", "examples", "test", "*.yml", "*.html", "*.ico", "*.md", "CNAME", ".*", "karma.*", "package.json"] } diff --git a/component.json b/component.json deleted file mode 100644 index 9fb9099e..00000000 --- a/component.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name" : "backbone", - "version" : "1.2.0", - "description" : "Give your JS App some Backbone with Models, Views, Collections, and Events.", - "keywords" : ["model", "view", "controller", "router", "server", "client", "browser"], - "repo" : "jashkenas/backbone", - "dependencies" : { - "jashkenas/underscore" : "*" - }, - "main" : "backbone.js", - "scripts" : ["backbone.js"], - "license" : "MIT" -} diff --git a/docs/backbone.html b/docs/backbone.html index 5d0e4699..eae389de 100644 --- a/docs/backbone.html +++ b/docs/backbone.html @@ -27,7 +27,7 @@
-
Backbone.js 1.2.0
+              
Backbone.js 1.3.3
 
@@ -40,7 +40,7 @@
-
(c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+              
(c) 2010-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
 Backbone may be freely distributed under the MIT license.
 For all details and documentation:
 http://backbonejs.org
@@ -48,7 +48,7 @@ http://backbonejs.org
             
             
             
-(function(factory) {
+(function(factory) {
@@ -64,8 +64,8 @@ We use self instead of window for WebWorker -
  var root = (typeof self == 'object' && self.self == self && self) ||
-            (typeof global == 'object' && global.global == global && global);
+
  var root = (typeof self == 'object' && self.self === self && self) ||
+            (typeof global == 'object' && global.global === global && global);
@@ -81,7 +81,7 @@ We use self instead of window for WebWorker
  if (typeof define === 'function' && define.amd) {
-    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
+ define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
@@ -115,7 +115,7 @@ others that may still expect a global Backbone.

  } else if (typeof exports !== 'undefined') {
     var _ = require('underscore'), $;
-    try { $ = require('jquery'); } catch(e) {}
+    try { $ = require('jquery'); } catch (e) {}
     factory(root, exports, _, $);
@@ -135,7 +135,7 @@ others that may still expect a global Backbone.

root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); } -}(function(root, Backbone, _, $) {
+})(function(root, Backbone, _, $) { @@ -187,12 +187,11 @@ restored later on, if noConflict is used.

-

Create local references to array methods we’ll want to use later.

+

Create a local reference to a common array method we’ll want to use later.

-
  var array = [];
-  var slice = array.slice;
+
  var slice = Array.prototype.slice;
@@ -207,7 +206,7 @@ restored later on, if noConflict is used.

-
  Backbone.VERSION = '1.2.0';
+
  Backbone.VERSION = '1.3.3';
@@ -239,7 +238,7 @@ to its previous owner. Returns a reference to this Backbone object.

-
  Backbone.noConflict = function() {
+            
  Backbone.noConflict = function() {
     root.Backbone = previousBackbone;
     return this;
   };
@@ -288,10 +287,41 @@ form param named model.

-

Backbone.Events

+

Proxy Backbone class methods to Underscore functions, wrapping the model’s +attributes object or collection’s models array behind the scenes.

+

collection.filter(function(model) { return model.get(‘age’) > 10 }); +collection.each(this.addView);

+

Function#apply can be slow so we use the method’s arg count, if we know it.

+
  var addMethod = function(length, method, attribute) {
+    switch (length) {
+      case 1: return function() {
+        return _[method](this[attribute]);
+      };
+      case 2: return function(value) {
+        return _[method](this[attribute], value);
+      };
+      case 3: return function(iteratee, context) {
+        return _[method](this[attribute], cb(iteratee, this), context);
+      };
+      case 4: return function(iteratee, defaultVal, context) {
+        return _[method](this[attribute], cb(iteratee, this), defaultVal, context);
+      };
+      default: return function() {
+        var args = slice.call(arguments);
+        args.unshift(this[attribute]);
+        return _[method].apply(_, args);
+      };
+    }
+  };
+  var addUnderscoreMethods = function(Class, methods, attribute) {
+    _.each(methods, function(length, method) {
+      if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
+    });
+  };
+ @@ -301,9 +331,23 @@ form param named model.

- +

Support collection.sortBy('attr') and collection.findWhere({id: 1}).

+
+
  var cb = function(iteratee, instance) {
+    if (_.isFunction(iteratee)) return iteratee;
+    if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
+    if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
+    return iteratee;
+  };
+  var modelMatcher = function(attrs) {
+    var matcher = _.matches(attrs);
+    return function(model) {
+      return matcher(model.attributes);
+    };
+  };
+ @@ -313,19 +357,10 @@ form param named model.

-

A module that can be mixed in to any object in order to provide it with -custom events. You may bind with on or remove with off callback -functions to an event; trigger-ing an event fires all callbacks in -succession.

-
var object = {};
-_.extend(object, Backbone.Events);
-object.on('expand', function(){ alert('expanded'); });
-object.trigger('expand');
-
+

Backbone.Events

+ -
  var Events = Backbone.Events = {};
- @@ -335,12 +370,9 @@ object.trigger('expand');
-

Regular expression used to split event strings.

- + -
  var eventSplitter = /\s+/;
- @@ -350,17 +382,18 @@ object.trigger('expand');
-

Iterates over the standard event, callback (as well as the fancy multiple -space-separated events "change blur", callback and jQuery-style event -maps {event: callback}), reducing them by manipulating memo. -Passes a normalized single event name and callback, as well as any -optional opts.

- +

A module that can be mixed in to any object in order to provide it with +a custom event channel. You may bind a callback to an event with on or +remove with off; trigger-ing an event fires all callbacks in +succession.

+
var object = {};
+_.extend(object, Backbone.Events);
+object.on('expand', function(){ alert('expanded'); });
+object.trigger('expand');
+
-
  var eventsApi = function(iteratee, memo, name, callback, opts) {
-    var i = 0, names;
-    if (name && typeof name === 'object') {
+
  var Events = Backbone.Events = {};
@@ -371,14 +404,11 @@ optional opts.

-

Handle event maps.

+

Regular expression used to split event strings.

-
      for (names = _.keys(name); i < names.length ; i++) {
-        memo = iteratee(memo, names[i], name[names[i]], opts);
-      }
-    } else if (name && eventSplitter.test(name)) {
+
  var eventSplitter = /\s+/;
@@ -389,18 +419,15 @@ optional opts.

-

Handle space separated event names.

+

Iterates over the standard event, callback (as well as the fancy multiple +space-separated events "change blur", callback and jQuery-style event +maps {event: callback}).

-
      for (names = name.split(eventSplitter); i < names.length; i++) {
-        memo = iteratee(memo, names[i], callback, opts);
-      }
-    } else {
-      memo = iteratee(memo, name, callback, opts);
-    }
-    return memo;
-  };
+
  var eventsApi = function(iteratee, events, name, callback, opts) {
+    var i = 0, names;
+    if (name && typeof name === 'object') {
@@ -411,14 +438,15 @@ optional opts.

-

Bind an event to a callback function. Passing "all" will bind -the callback to all events fired.

+

Handle event maps.

-
  Events.on = function(name, callback, context) {
-    return internalOn(this, name, callback, context);
-  };
+
      if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
+      for (names = _.keys(name); i < names.length ; i++) {
+        events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
+      }
+    } else if (name && eventSplitter.test(name)) {
@@ -429,16 +457,69 @@ the callback to all events fired.

-

An internal use on function, used to guard the listening argument from -the public API.

+

Handle space-separated event names by delegating them individually.

-
  var internalOn = function(obj, name, callback, context, listening) {
+            
      for (names = name.split(eventSplitter); i < names.length; i++) {
+        events = iteratee(events, names[i], callback, opts);
+      }
+    } else {
+ + + + +
  • +
    + +
    + +
    +

    Finally, standard events.

    + +
    + +
          events = iteratee(events, name, callback, opts);
    +    }
    +    return events;
    +  };
    + +
  • + + +
  • +
    + +
    + +
    +

    Bind an event to a callback function. Passing "all" will bind +the callback to all events fired.

    + +
    + +
      Events.on = function(name, callback, context) {
    +    return internalOn(this, name, callback, context);
    +  };
    + +
  • + + +
  • +
    + +
    + +
    +

    Guard the listening argument from the public API.

    + +
    + +
      var internalOn = function(obj, name, callback, context, listening) {
         obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
    -        context: context,
    -        ctx: obj,
    -        listening: listening
    +      context: context,
    +      ctx: obj,
    +      listening: listening
         });
     
         if (listening) {
    @@ -452,18 +533,19 @@ the public API.

  • -
  • +
  • - +

    Inversion-of-control versions of on. Tell this object to listen to -an event in another object… keeping track of what it’s listening to.

    +an event in another object… keeping track of what it’s listening to +for easier unbinding later.

    -
      Events.listenTo =  function(obj, name, callback) {
    +            
      Events.listenTo = function(obj, name, callback) {
         if (!obj) return this;
         var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
         var listeningTo = this._listeningTo || (this._listeningTo = {});
    @@ -472,11 +554,11 @@ an event in another object… keeping track of what it’s listening to.

  • -
  • +
  • - +

    This object is not listening to any other events on obj yet. Setup the necessary references to track the listening callbacks.

    @@ -491,11 +573,11 @@ Setup the necessary references to track the listening callbacks.

  • -
  • +
  • - +

    Bind callbacks on obj, and keep track of them on listening.

    @@ -508,96 +590,25 @@ Setup the necessary references to track the listening callbacks.

  • -
  • -
    - -
    - -
    -

    The reducing API that adds a callback to the events object.

    - -
    - -
      var onApi = function(events, name, callback, options) {
    -    if (callback) {
    -      var handlers = events[name] || (events[name] = []);
    -      var context = options.context, ctx = options.ctx, listening = options.listening;
    -      if (listening) listening.count++;
    -
    -      handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening });
    -    }
    -    return events;
    -  };
    - -
  • - - -
  • -
    - -
    - -
    -

    Remove one or many callbacks. If context is null, removes all -callbacks with that function. If callback is null, removes all -callbacks for the event. If name is null, removes all bound -callbacks for all events.

    - -
    - -
      Events.off =  function(name, callback, context) {
    -    if (!this._events) return this;
    -    this._events = eventsApi(offApi, this._events, name, callback, {
    -        context: context,
    -        listeners: this._listeners
    -    });
    -    return this;
    -  };
    - -
  • - - -
  • -
    - -
    - -
    -

    Tell this object to stop listening to either specific events … or -to every object it’s currently listening to.

    - -
    - -
      Events.stopListening =  function(obj, name, callback) {
    -    var listeningTo = this._listeningTo;
    -    if (!listeningTo) return this;
    -
    -    var ids = obj ? [obj._listenId] : _.keys(listeningTo);
    -
    -    for (var i = 0; i < ids.length; i++) {
    -      var listening = listeningTo[ids[i]];
    - -
  • - -
  • -

    If listening doesn’t exist, this object is not currently -listening to obj. Break out early.

    +

    The reducing API that adds a callback to the events object.

    -
          if (!listening) break;
    +            
      var onApi = function(events, name, callback, options) {
    +    if (callback) {
    +      var handlers = events[name] || (events[name] = []);
    +      var context = options.context, ctx = options.ctx, listening = options.listening;
    +      if (listening) listening.count++;
     
    -      listening.obj.off(name, callback, this);
    +      handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
         }
    -    if (_.isEmpty(listeningTo)) this._listeningTo = void 0;
    -
    -    return this;
    +    return events;
       };
  • @@ -609,11 +620,21 @@ listening to obj. Break out early.

    -

    The reducing API that removes a callback from the events object.

    +

    Remove one or many callbacks. If context is null, removes all +callbacks with that function. If callback is null, removes all +callbacks for the event. If name is null, removes all bound +callbacks for all events.

    -
      var offApi = function(events, name, callback, options) {
    +
      Events.off = function(name, callback, context) {
    +    if (!this._events) return this;
    +    this._events = eventsApi(offApi, this._events, name, callback, {
    +      context: context,
    +      listeners: this._listeners
    +    });
    +    return this;
    +  };
    @@ -624,14 +645,19 @@ listening to obj. Break out early.

    -

    No events to consider.

    +

    Tell this object to stop listening to either specific events … or +to every object it’s currently listening to.

    -
        if (!events) return;
    +            
      Events.stopListening = function(obj, name, callback) {
    +    var listeningTo = this._listeningTo;
    +    if (!listeningTo) return this;
     
    -    var i = 0, length, listening;
    -    var context = options.context, listeners = options.listeners;
    + var ids = obj ? [obj._listenId] : _.keys(listeningTo); + + for (var i = 0; i < ids.length; i++) { + var listening = listeningTo[ids[i]];
    @@ -642,6 +668,47 @@ listening to obj. Break out early.

    +

    If listening doesn’t exist, this object is not currently +listening to obj. Break out early.

    + + + +
          if (!listening) break;
    +
    +      listening.obj.off(name, callback, this);
    +    }
    +
    +    return this;
    +  };
    + + + + +
  • +
    + +
    + +
    +

    The reducing API that removes a callback from the events object.

    + +
    + +
      var offApi = function(events, name, callback, options) {
    +    if (!events) return;
    +
    +    var i = 0, listening;
    +    var context = options.context, listeners = options.listeners;
    + +
  • + + +
  • +
    + +
    + +

    Delete all events listeners and “drop” events.

    @@ -664,11 +731,11 @@ listening to obj. Break out early.

  • -
  • +
  • - +

    Bail out if there are no events stored.

    @@ -679,11 +746,11 @@ listening to obj. Break out early.

  • -
  • +
  • - +

    Replace events if there are any remaining. Otherwise, clean up.

    @@ -710,11 +777,11 @@ listening to obj. Break out early.

  • -
  • +
  • - +

    Update tail event if the list has any events. Otherwise, clean up.

    @@ -726,42 +793,7 @@ listening to obj. Break out early.

    delete events[name]; } } - if (_.size(events)) return events; - };
    - -
  • - - -
  • -
    - -
    - -
    -

    Bind an event to only be triggered a single time. After the first time -the callback is invoked, it will be removed. When multiple events are -passed in using the space-separated syntax, the event will fire once for every -event you passed in, not once for a combination of all events

    - -
    - -
      Events.once =  function(name, callback, context) {
    - -
  • - - -
  • -
    - -
    - -
    -

    Map the event into a {event: once} object.

    - -
    - -
        var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this));
    -    return this.on(events, void 0, context);
    +    return events;
       };
  • @@ -773,11 +805,14 @@ event you passed in, not once for a combination of all events

    -

    Inversion-of-control versions of once.

    +

    Bind an event to only be triggered a single time. After the first time +the callback is invoked, its listener will be removed. If multiple events +are passed in using the space-separated syntax, the handler will fire +once for each event, not once for a combination of all events.

    -
      Events.listenToOnce =  function(obj, name, callback) {
    +
      Events.once = function(name, callback, context) {
    @@ -792,8 +827,9 @@ event you passed in, not once for a combination of all events

    -
        var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj));
    -    return this.listenTo(obj, events);
    +            
        var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this));
    +    if (typeof name === 'string' && context == null) callback = void 0;
    +    return this.on(events, callback, context);
       };
    @@ -805,14 +841,46 @@ event you passed in, not once for a combination of all events

    -

    Reduces the event callbacks into a map of {event: onceWrapper}. -offer unbinds the onceWrapper after it as been called.

    +

    Inversion-of-control versions of once.

    -
      var onceMap = function(map, name, callback, offer) {
    +            
      Events.listenToOnce = function(obj, name, callback) {
    + + + + +
  • +
    + +
    + +
    +

    Map the event into a {event: once} object.

    + +
    + +
        var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj));
    +    return this.listenTo(obj, events);
    +  };
    + +
  • + + +
  • +
    + +
    + +
    +

    Reduces the event callbacks into a map of {event: onceWrapper}. +offer unbinds the onceWrapper after it has been called.

    + +
    + +
      var onceMap = function(map, name, callback, offer) {
         if (callback) {
    -      var once = map[name] = _.once(function() {
    +      var once = map[name] = _.once(function() {
             offer(name, once);
             callback.apply(this, arguments);
           });
    @@ -824,11 +892,11 @@ event you passed in, not once for a combination of all events

  • -
  • +
  • - +

    Trigger one or many events, firing all bound callbacks. Callbacks are passed the same arguments as trigger is, apart from the event name @@ -837,7 +905,7 @@ receive the true name of the event as the first argument).

    -
      Events.trigger =  function(name) {
    +            
      Events.trigger = function(name) {
         if (!this._events) return this;
     
         var length = Math.max(0, arguments.length - 1);
    @@ -851,17 +919,17 @@ receive the true name of the event as the first argument).

  • -
  • +
  • - +

    Handles triggering the appropriate event callbacks.

    -
      var triggerApi = function(objEvents, name, cb, args) {
    +            
      var triggerApi = function(objEvents, name, callback, args) {
         if (objEvents) {
           var events = objEvents[name];
           var allEvents = objEvents.all;
    @@ -875,11 +943,11 @@ receive the true name of the event as the first argument).

  • -
  • +
  • - +

    A difficult-to-believe, but optimized internal dispatch function for triggering events. Tries to keep the usual cases speedy (most internal @@ -887,8 +955,8 @@ Backbone events have 3 arguments).

    -
      var triggerEvents = function(events, args) {
    -    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
    +            
      var triggerEvents = function(events, args) {
    +    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
         switch (args.length) {
           case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
           case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
    @@ -901,52 +969,11 @@ Backbone events have 3 arguments).

  • -
  • +
  • - -
    -

    Proxy Underscore methods to a Backbone class’ prototype using a -particular attribute as the data argument

    - -
    - -
      var addMethod = function(length, method, attribute) {
    -    switch (length) {
    -      case 1: return function() {
    -        return _[method](this[attribute]);
    -      };
    -      case 2: return function(value) {
    -        return _[method](this[attribute], value);
    -      };
    -      case 3: return function(iteratee, context) {
    -        return _[method](this[attribute], iteratee, context);
    -      };
    -      case 4: return function(iteratee, defaultVal, context) {
    -        return _[method](this[attribute], iteratee, defaultVal, context);
    -      };
    -      default: return function() {
    -        var args = slice.call(arguments);
    -        args.unshift(this[attribute]);
    -        return _[method].apply(_, args);
    -      };
    -    }
    -  };
    -  var addUnderscoreMethods = function(Class, methods, attribute) {
    -    _.each(methods, function(length, method) {
    -      if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
    -    });
    -  };
    - -
  • - - -
  • -
    - -
    - +

    Aliases for backwards compatibility.

    @@ -958,11 +985,11 @@ particular attribute as the data argument

  • -
  • +
  • - +

    Allow the Backbone object to serve as a global event bus, for folks who want global “pubsub” in a convenient place.

    @@ -974,26 +1001,14 @@ want global “pubsub” in a convenient place.

  • -
  • -
    - -
    - -
    -

    Backbone.Model

    - -
    - -
  • - -
  • - +

    Backbone.Model

    +
  • @@ -1005,11 +1020,7 @@ want global “pubsub” in a convenient place.

    -

    Backbone Models are the basic data object in the framework — -frequently representing a row in a table in a database on your server. -A discrete chunk of data and a bunch of useful, related methods for -performing computations and transformations on that data.

    - +
    @@ -1021,24 +1032,13 @@ performing computations and transformations on that data.

    -

    Create a new model with the specified attributes. A client id (cid) -is automatically generated and assigned for you.

    +

    Backbone Models are the basic data object in the framework – +frequently representing a row in a table in a database on your server. +A discrete chunk of data and a bunch of useful, related methods for +performing computations and transformations on that data.

    -
      var Model = Backbone.Model = function(attributes, options) {
    -    var attrs = attributes || {};
    -    options || (options = {});
    -    this.cid = _.uniqueId(this.cidPrefix);
    -    this.attributes = {};
    -    if (options.collection) this.collection = options.collection;
    -    if (options.parse) attrs = this.parse(attrs, options) || {};
    -    attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
    -    this.set(attrs, options);
    -    this.changed = {};
    -    this.initialize.apply(this, arguments);
    -  };
    - @@ -1048,11 +1048,24 @@ is automatically generated and assigned for you.

    -

    Attach all inheritable methods to the Model prototype.

    +

    Create a new model with the specified attributes. A client id (cid) +is automatically generated and assigned for you.

    -
      _.extend(Model.prototype, Events, {
    +
      var Model = Backbone.Model = function(attributes, options) {
    +    var attrs = attributes || {};
    +    options || (options = {});
    +    this.cid = _.uniqueId(this.cidPrefix);
    +    this.attributes = {};
    +    if (options.collection) this.collection = options.collection;
    +    if (options.parse) attrs = this.parse(attrs, options) || {};
    +    var defaults = _.result(this, 'defaults');
    +    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
    +    this.set(attrs, options);
    +    this.changed = {};
    +    this.initialize.apply(this, arguments);
    +  };
    @@ -1063,11 +1076,11 @@ is automatically generated and assigned for you.

    -

    A hash of attributes whose current and previous value differ.

    +

    Attach all inheritable methods to the Model prototype.

    -
        changed: null,
    +
      _.extend(Model.prototype, Events, {
    @@ -1078,11 +1091,11 @@ is automatically generated and assigned for you.

    -

    The value returned during the last failed validation.

    +

    A hash of attributes whose current and previous value differ.

    -
        validationError: null,
    +
        changed: null,
    @@ -1093,6 +1106,21 @@ is automatically generated and assigned for you.

    +

    The value returned during the last failed validation.

    + + + +
        validationError: null,
    + + + + +
  • +
    + +
    + +

    The default name for the JSON id attribute is "id". MongoDB and CouchDB users may want to set this to "_id".

    @@ -1103,11 +1131,11 @@ CouchDB users may want to set this to "_id".

  • -
  • +
  • - +

    The prefix is used to create the client id which is used to identify models locally. You may want to override this if you’re experiencing name clashes with model ids.

    @@ -1119,35 +1147,18 @@ You may want to override this if you’re experiencing name clashes with model i
  • -
  • -
    - -
    - -
    -

    Initialize is an empty function by default. Override it with your own -initialization logic.

    - -
    - -
        initialize: function(){},
    - -
  • - -
  • -

    Return a copy of the model’s attributes object.

    +

    Initialize is an empty function by default. Override it with your own +initialization logic.

    -
        toJSON: function(options) {
    -      return _.clone(this.attributes);
    -    },
    +
        initialize: function(){},
  • @@ -1158,13 +1169,12 @@ initialization logic.

    -

    Proxy Backbone.sync by default — but override this if you need -custom syncing semantics for this particular model.

    +

    Return a copy of the model’s attributes object.

    -
        sync: function() {
    -      return Backbone.sync.apply(this, arguments);
    +            
        toJSON: function(options) {
    +      return _.clone(this.attributes);
         },
    @@ -1176,12 +1186,13 @@ custom syncing semantics for this particular model.

    -

    Get the value of an attribute.

    +

    Proxy Backbone.sync by default – but override this if you need +custom syncing semantics for this particular model.

    -
        get: function(attr) {
    -      return this.attributes[attr];
    +            
        sync: function() {
    +      return Backbone.sync.apply(this, arguments);
         },
    @@ -1193,12 +1204,12 @@ custom syncing semantics for this particular model.

    -

    Get the HTML-escaped value of an attribute.

    +

    Get the value of an attribute.

    -
        escape: function(attr) {
    -      return _.escape(this.get(attr));
    +            
        get: function(attr) {
    +      return this.attributes[attr];
         },
    @@ -1210,13 +1221,12 @@ custom syncing semantics for this particular model.

    -

    Returns true if the attribute contains a value that is not null -or undefined.

    +

    Get the HTML-escaped value of an attribute.

    -
        has: function(attr) {
    -      return this.get(attr) != null;
    +            
        escape: function(attr) {
    +      return _.escape(this.get(attr));
         },
    @@ -1228,12 +1238,13 @@ or undefined.

    -

    Special-cased proxy to underscore’s _.matches method.

    +

    Returns true if the attribute contains a value that is not null +or undefined.

    -
        matches: function(attrs) {
    -      return !!_.iteratee(attrs, this)(this.attributes);
    +            
        has: function(attr) {
    +      return this.get(attr) != null;
         },
    @@ -1245,15 +1256,13 @@ or undefined.

    -

    Set a hash of model attributes on the object, firing "change". This is -the core primitive operation of a model, updating the data and notifying -anyone who needs to know about the change in state. The heart of the beast.

    +

    Special-cased proxy to underscore’s _.matches method.

    -
        set: function(key, val, options) {
    -      var attr, attrs, unset, changes, silent, changing, prev, current;
    -      if (key == null) return this;
    +
        matches: function(attrs) {
    +      return !!_.iteratee(attrs, this)(this.attributes);
    +    },
    @@ -1264,11 +1273,30 @@ anyone who needs to know about the change in state. The heart of the beast.

    +

    Set a hash of model attributes on the object, firing "change". This is +the core primitive operation of a model, updating the data and notifying +anyone who needs to know about the change in state. The heart of the beast.

    + +
    + +
        set: function(key, val, options) {
    +      if (key == null) return this;
    + + + + +
  • +
    + +
    + +

    Handle both "key", value and {key: value} -style arguments.

    -
          if (typeof key === 'object') {
    +            
          var attrs;
    +      if (typeof key === 'object') {
             attrs = key;
             options = val;
           } else {
    @@ -1280,11 +1308,11 @@ anyone who needs to know about the change in state. The heart of the beast.

  • -
  • +
  • - +

    Run validation.

    @@ -1295,42 +1323,30 @@ anyone who needs to know about the change in state. The heart of the beast.

  • -
  • -
    - -
    - -
    -

    Extract attributes and options.

    - -
    - -
          unset           = options.unset;
    -      silent          = options.silent;
    -      changes         = [];
    -      changing        = this._changing;
    -      this._changing  = true;
    -
    -      if (!changing) {
    -        this._previousAttributes = _.clone(this.attributes);
    -        this.changed = {};
    -      }
    -      current = this.attributes, prev = this._previousAttributes;
    - -
  • - -
  • -

    Check for changes of id.

    +

    Extract attributes and options.

    -
          if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
    +
          var unset      = options.unset;
    +      var silent     = options.silent;
    +      var changes    = [];
    +      var changing   = this._changing;
    +      this._changing = true;
    +
    +      if (!changing) {
    +        this._previousAttributes = _.clone(this.attributes);
    +        this.changed = {};
    +      }
    +
    +      var current = this.attributes;
    +      var changed = this.changed;
    +      var prev    = this._previousAttributes;
  • @@ -1345,13 +1361,13 @@ anyone who needs to know about the change in state. The heart of the beast.

    -
          for (attr in attrs) {
    +            
          for (var attr in attrs) {
             val = attrs[attr];
             if (!_.isEqual(current[attr], val)) changes.push(attr);
             if (!_.isEqual(prev[attr], val)) {
    -          this.changed[attr] = val;
    +          changed[attr] = val;
             } else {
    -          delete this.changed[attr];
    +          delete changed[attr];
             }
             unset ? delete current[attr] : current[attr] = val;
           }
    @@ -1365,6 +1381,21 @@ anyone who needs to know about the change in state. The heart of the beast.

    +

    Update the id.

    + +
    + +
          if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);
    + + + + +
  • +
    + +
    + +

    Trigger all relevant attribute changes.

    @@ -1379,11 +1410,11 @@ anyone who needs to know about the change in state. The heart of the beast.

  • -
  • +
  • - +

    You might be wondering why there’s a while loop here. Changes can be recursively nested within "change" events.

    @@ -1406,38 +1437,19 @@ be recursively nested within "change" events.

  • -
  • -
    - -
    - -
    -

    Remove an attribute from the model, firing "change". unset is a noop -if the attribute doesn’t exist.

    - -
    - -
        unset: function(attr, options) {
    -      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
    -    },
    - -
  • - -
  • -

    Clear all attributes on the model, firing "change".

    +

    Remove an attribute from the model, firing "change". unset is a noop +if the attribute doesn’t exist.

    -
        clear: function(options) {
    -      var attrs = {};
    -      for (var key in this.attributes) attrs[key] = void 0;
    -      return this.set(attrs, _.extend({}, options, {unset: true}));
    +            
        unset: function(attr, options) {
    +      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
         },
  • @@ -1449,14 +1461,14 @@ if the attribute doesn’t exist.

    -

    Determine if the model has changed since the last "change" event. -If you specify an attribute name, determine if that attribute has changed.

    +

    Clear all attributes on the model, firing "change".

    -
        hasChanged: function(attr) {
    -      if (attr == null) return !_.isEmpty(this.changed);
    -      return _.has(this.changed, attr);
    +            
        clear: function(options) {
    +      var attrs = {};
    +      for (var key in this.attributes) attrs[key] = void 0;
    +      return this.set(attrs, _.extend({}, options, {unset: true}));
         },
    @@ -1468,24 +1480,14 @@ If you specify an attribute name, determine if that attribute has changed.

    -

    Return an object containing all the attributes that have changed, or -false if there are no changed attributes. Useful for determining what -parts of a view need to be updated and/or what attributes need to be -persisted to the server. Unset attributes will be set to undefined. -You can also pass an attributes object to diff against the model, -determining if there would be a change.

    +

    Determine if the model has changed since the last "change" event. +If you specify an attribute name, determine if that attribute has changed.

    -
        changedAttributes: function(diff) {
    -      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
    -      var val, changed = false;
    -      var old = this._changing ? this._previousAttributes : this.attributes;
    -      for (var attr in diff) {
    -        if (_.isEqual(old[attr], (val = diff[attr]))) continue;
    -        (changed || (changed = {}))[attr] = val;
    -      }
    -      return changed;
    +            
        hasChanged: function(attr) {
    +      if (attr == null) return !_.isEmpty(this.changed);
    +      return _.has(this.changed, attr);
         },
    @@ -1497,14 +1499,25 @@ determining if there would be a change.

    -

    Get the previous value of an attribute, recorded at the time the last -"change" event was fired.

    +

    Return an object containing all the attributes that have changed, or +false if there are no changed attributes. Useful for determining what +parts of a view need to be updated and/or what attributes need to be +persisted to the server. Unset attributes will be set to undefined. +You can also pass an attributes object to diff against the model, +determining if there would be a change.

    -
        previous: function(attr) {
    -      if (attr == null || !this._previousAttributes) return null;
    -      return this._previousAttributes[attr];
    +            
        changedAttributes: function(diff) {
    +      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
    +      var old = this._changing ? this._previousAttributes : this.attributes;
    +      var changed = {};
    +      for (var attr in diff) {
    +        var val = diff[attr];
    +        if (_.isEqual(old[attr], val)) continue;
    +        changed[attr] = val;
    +      }
    +      return _.size(changed) ? changed : false;
         },
    @@ -1516,13 +1529,14 @@ determining if there would be a change.

    -

    Get all of the attributes of the model at the time of the previous -"change" event.

    +

    Get the previous value of an attribute, recorded at the time the last +"change" event was fired.

    -
        previousAttributes: function() {
    -      return _.clone(this._previousAttributes);
    +            
        previous: function(attr) {
    +      if (attr == null || !this._previousAttributes) return null;
    +      return this._previousAttributes[attr];
         },
    @@ -1534,23 +1548,13 @@ determining if there would be a change.

    -

    Fetch the model from the server, merging the response with the model’s -local attributes. Any changed attributes will trigger a “change” event.

    +

    Get all of the attributes of the model at the time of the previous +"change" event.

    -
        fetch: function(options) {
    -      options = options ? _.clone(options) : {};
    -      if (options.parse === void 0) options.parse = true;
    -      var model = this;
    -      var success = options.success;
    -      options.success = function(resp) {
    -        if (!model.set(model.parse(resp, options), options)) return false;
    -        if (success) success.call(options.context, model, resp, options);
    -        model.trigger('sync', model, resp, options);
    -      };
    -      wrapError(this, options);
    -      return this.sync('read', this, options);
    +            
        previousAttributes: function() {
    +      return _.clone(this._previousAttributes);
         },
    @@ -1562,14 +1566,24 @@ local attributes. Any changed attributes will trigger a “change” event.

    -

    Set a hash of model attributes, and sync the model to the server. -If the server returns an attributes hash that differs, the model’s -state will be set again.

    +

    Fetch the model from the server, merging the response with the model’s +local attributes. Any changed attributes will trigger a “change” event.

    -
        save: function(key, val, options) {
    -      var attrs, method, xhr, attributes = this.attributes, wait;
    +
        fetch: function(options) {
    +      options = _.extend({parse: true}, options);
    +      var model = this;
    +      var success = options.success;
    +      options.success = function(resp) {
    +        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
    +        if (!model.set(serverAttrs, options)) return false;
    +        if (success) success.call(options.context, model, resp, options);
    +        model.trigger('sync', model, resp, options);
    +      };
    +      wrapError(this, options);
    +      return this.sync('read', this, options);
    +    },
    @@ -1580,19 +1594,13 @@ state will be set again.

    -

    Handle both "key", value and {key: value} -style arguments.

    +

    Set a hash of model attributes, and sync the model to the server. +If the server returns an attributes hash that differs, the model’s +state will be set again.

    -
          if (key == null || typeof key === 'object') {
    -        attrs = key;
    -        options = val;
    -      } else {
    -        (attrs = {})[key] = val;
    -      }
    -
    -      options = _.extend({validate: true}, options);
    -      wait = options.wait;
    +
        save: function(key, val, options) {
    @@ -1603,17 +1611,20 @@ state will be set again.

    -

    If we’re not waiting and attributes exist, save acts as -set(attr).save(null, opts) with validation. Otherwise, check if -the model will be valid when the attributes, if any, are set.

    +

    Handle both "key", value and {key: value} -style arguments.

    -
          if (attrs && !wait) {
    -        if (!this.set(attrs, options)) return false;
    +            
          var attrs;
    +      if (key == null || typeof key === 'object') {
    +        attrs = key;
    +        options = val;
           } else {
    -        if (!this._validate(attrs, options)) return false;
    -      }
    + (attrs = {})[key] = val; + } + + options = _.extend({validate: true, parse: true}, options); + var wait = options.wait;
    @@ -1624,12 +1635,16 @@ the model will be valid when the attributes, if any, are set.

    -

    Set temporary attributes if {wait: true}.

    +

    If we’re not waiting and attributes exist, save acts as +set(attr).save(null, opts) with validation. Otherwise, check if +the model will be valid when the attributes, if any, are set.

    -
          if (attrs && wait) {
    -        this.attributes = _.extend({}, attributes, attrs);
    +            
          if (attrs && !wait) {
    +        if (!this.set(attrs, options)) return false;
    +      } else if (!this._validate(attrs, options)) {
    +        return false;
           }
    @@ -1646,10 +1661,10 @@ updated with the server-side state.

    -
          if (options.parse === void 0) options.parse = true;
    -      var model = this;
    +            
          var model = this;
           var success = options.success;
    -      options.success = function(resp) {
    + var attributes = this.attributes; + options.success = function(resp) {
    @@ -1666,18 +1681,12 @@ updated with the server-side state.

            model.attributes = attributes;
             var serverAttrs = options.parse ? model.parse(resp, options) : resp;
    -        if (wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
    -        if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
    -          return false;
    -        }
    +        if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
    +        if (serverAttrs && !model.set(serverAttrs, options)) return false;
             if (success) success.call(options.context, model, resp, options);
             model.trigger('sync', model, resp, options);
           };
    -      wrapError(this, options);
    -
    -      method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
    -      if (method === 'patch' && !options.attrs) options.attrs = attrs;
    -      xhr = this.sync(method, this, options);
    + wrapError(this, options);
    @@ -1688,14 +1697,15 @@ updated with the server-side state.

    -

    Restore attributes.

    +

    Set temporary attributes if {wait: true} to properly find new ids.

    -
          if (attrs && wait) this.attributes = attributes;
    +            
          if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);
     
    -      return xhr;
    -    },
    + var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); + if (method === 'patch' && !options.attrs) options.attrs = attrs; + var xhr = this.sync(method, this, options);
    @@ -1706,24 +1716,42 @@ updated with the server-side state.

    +

    Restore attributes.

    + +
    + +
          this.attributes = attributes;
    +
    +      return xhr;
    +    },
    + + + + +
  • +
    + +
    + +

    Destroy this model on the server if it was already persisted. Optimistically removes the model from its collection, if it has one. If wait: true is passed, waits for the server to respond before removal.

    -
        destroy: function(options) {
    +            
        destroy: function(options) {
           options = options ? _.clone(options) : {};
           var model = this;
           var success = options.success;
           var wait = options.wait;
     
    -      var destroy = function() {
    +      var destroy = function() {
             model.stopListening();
             model.trigger('destroy', model, model.collection, options);
           };
     
    -      options.success = function(resp) {
    +      options.success = function(resp) {
             if (wait) destroy();
             if (success) success.call(options.context, model, resp, options);
             if (!model.isNew()) model.trigger('sync', model, resp, options);
    @@ -1743,44 +1771,26 @@ If wait: true is passed, waits for the server to respond before rem
             
  • -
  • -
    - -
    - -
    -

    Default URL for the model’s representation on the server — if you’re -using Backbone’s restful methods, override this to change the endpoint -that will be called.

    - -
    - -
        url: function() {
    -      var base =
    -        _.result(this, 'urlRoot') ||
    -        _.result(this.collection, 'url') ||
    -        urlError();
    -      if (this.isNew()) return base;
    -      var id = this.id || this.attributes[this.idAttribute];
    -      return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(id);
    -    },
    - -
  • - -
  • -

    parse converts a response into the hash of attributes to be set on -the model. The default implementation is just to pass the response along.

    +

    Default URL for the model’s representation on the server – if you’re +using Backbone’s restful methods, override this to change the endpoint +that will be called.

    -
        parse: function(resp, options) {
    -      return resp;
    +            
        url: function() {
    +      var base =
    +        _.result(this, 'urlRoot') ||
    +        _.result(this.collection, 'url') ||
    +        urlError();
    +      if (this.isNew()) return base;
    +      var id = this.get(this.idAttribute);
    +      return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
         },
  • @@ -1792,12 +1802,13 @@ the model. The default implementation is just to pass the response along.

    -

    Create a new model with identical attributes to this one.

    +

    parse converts a response into the hash of attributes to be set on +the model. The default implementation is just to pass the response along.

    -
        clone: function() {
    -      return new this.constructor(this.attributes);
    +            
        parse: function(resp, options) {
    +      return resp;
         },
    @@ -1809,12 +1820,12 @@ the model. The default implementation is just to pass the response along.

    -

    A model is new if it has never been saved to the server, and lacks an id.

    +

    Create a new model with identical attributes to this one.

    -
        isNew: function() {
    -      return !this.has(this.idAttribute);
    +            
        clone: function() {
    +      return new this.constructor(this.attributes);
         },
    @@ -1826,12 +1837,12 @@ the model. The default implementation is just to pass the response along.

    -

    Check if the model is currently in a valid state.

    +

    A model is new if it has never been saved to the server, and lacks an id.

    -
        isValid: function(options) {
    -      return this._validate({}, _.extend(options || {}, { validate: true }));
    +            
        isNew: function() {
    +      return !this.has(this.idAttribute);
         },
    @@ -1843,12 +1854,29 @@ the model. The default implementation is just to pass the response along.

    +

    Check if the model is currently in a valid state.

    + +
    + +
        isValid: function(options) {
    +      return this._validate({}, _.extend({}, options, {validate: true}));
    +    },
    + + + + +
  • +
    + +
    + +

    Run validation against the next complete set of model attributes, returning true if all is well. Otherwise, fire an "invalid" event.

    -
        _validate: function(attrs, options) {
    +            
        _validate: function(attrs, options) {
           if (!options.validate || !this.validate) return true;
           attrs = _.extend({}, this.attributes, attrs);
           var error = this.validationError = this.validate(attrs, options) || null;
    @@ -1862,33 +1890,19 @@ returning true if all is well. Otherwise, fire an "inval
             
  • -
  • -
    - -
    - -
    -

    Underscore methods that we want to implement on the Model.

    - -
    - -
      var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
    -      omit: 0, chain: 1, isEmpty: 1 };
    - -
  • - -
  • -

    Mix in each Underscore method as a proxy to Model#attributes.

    +

    Underscore methods that we want to implement on the Model, mapped to the +number of arguments they take.

    -
      addUnderscoreMethods(Model, modelMethods, 'attributes');
    +
      var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
    +      omit: 0, chain: 1, isEmpty: 1};
  • @@ -1899,10 +1913,12 @@ returning true if all is well. Otherwise, fire an "inval
    -

    Backbone.Collection

    +

    Mix in each Underscore method as a proxy to Model#attributes.

    +
      addUnderscoreMethods(Model, modelMethods, 'attributes');
    + @@ -1912,7 +1928,8 @@ returning true if all is well. Otherwise, fire an "inval
    - +

    Backbone.Collection

    +
    @@ -1924,13 +1941,7 @@ returning true if all is well. Otherwise, fire an "inval
    -

    If models tend to represent a single row of data, a Backbone Collection is -more analogous to a table full of data … or a small slice or page of that -table, or a collection of rows that belong together for a particular reason -— all of the messages in this particular folder, all of the documents -belonging to this particular author, and so on. Collections maintain -indexes of their models, both in order, and for lookup by id.

    - +
    @@ -1942,13 +1953,31 @@ indexes of their models, both in order, and for lookup by id.

    +

    If models tend to represent a single row of data, a Backbone Collection is +more analogous to a table full of data … or a small slice or page of that +table, or a collection of rows that belong together for a particular reason +– all of the messages in this particular folder, all of the documents +belonging to this particular author, and so on. Collections maintain +indexes of their models, both in order, and for lookup by id.

    + +
    + + + + +
  • +
    + +
    + +

    Create a new Collection, perhaps to contain a specific type of model. If a comparator is specified, the Collection will maintain its models in sort order, as they’re added and removed.

    -
      var Collection = Backbone.Collection = function(models, options) {
    +            
      var Collection = Backbone.Collection = function(models, options) {
         options || (options = {});
         if (options.model) this.model = options.model;
         if (options.comparator !== void 0) this.comparator = options.comparator;
    @@ -1960,11 +1989,11 @@ its models in sort order, as they’re added and removed.

  • -
  • +
  • - +

    Default options for Collection#set.

    @@ -1976,11 +2005,34 @@ its models in sort order, as they’re added and removed.

  • -
  • +
  • - + +
    +

    Splices insert into array at index at.

    + +
    + +
      var splice = function(array, insert, at) {
    +    at = Math.min(Math.max(at, 0), array.length);
    +    var tail = Array(array.length - at);
    +    var length = insert.length;
    +    var i;
    +    for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
    +    for (i = 0; i < length; i++) array[i + at] = insert[i];
    +    for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
    +  };
    + +
  • + + +
  • +
    + +
    +

    Define the Collection’s inheritable methods.

    @@ -1991,11 +2043,11 @@ its models in sort order, as they’re added and removed.

  • -
  • +
  • - +

    The default model for a collection is just a Backbone.Model. This should be overridden in most cases.

    @@ -2007,53 +2059,18 @@ This should be overridden in most cases.

  • -
  • -
    - -
    - -
    -

    Initialize is an empty function by default. Override it with your own -initialization logic.

    - -
    - -
        initialize: function(){},
    - -
  • - - -
  • -
    - -
    - -
    -

    The JSON representation of a Collection is an array of the -models’ attributes.

    - -
    - -
        toJSON: function(options) {
    -      return this.map(function(model){ return model.toJSON(options); });
    -    },
    - -
  • - -
  • -

    Proxy Backbone.sync by default.

    +

    Initialize is an empty function by default. Override it with your own +initialization logic.

    -
        sync: function() {
    -      return Backbone.sync.apply(this, arguments);
    -    },
    +
        initialize: function(){},
  • @@ -2064,12 +2081,13 @@ models’ attributes.

    -

    Add a model, or list of models to the set.

    +

    The JSON representation of a Collection is an array of the +models’ attributes.

    -
        add: function(models, options) {
    -      return this.set(models, _.extend({merge: false}, options, addOptions));
    +            
        toJSON: function(options) {
    +      return this.map(function(model) { return model.toJSON(options); });
         },
    @@ -2081,17 +2099,12 @@ models’ attributes.

    -

    Remove a model, or a list of models from the set.

    +

    Proxy Backbone.sync by default.

    -
        remove: function(models, options) {
    -      var singular = !_.isArray(models), removed;
    -      models = singular ? [models] : _.clone(models);
    -      options || (options = {});
    -      removed = this._removeModels(models, options);
    -      if (!options.silent && removed) this.trigger('update', this, options);
    -      return singular ? models[0] : models;
    +            
        sync: function() {
    +      return Backbone.sync.apply(this, arguments);
         },
    @@ -2103,28 +2116,15 @@ models’ attributes.

    -

    Update a collection by set-ing a new list of models, adding new ones, -removing models that are no longer present, and merging models that -already exist in the collection, as necessary. Similar to Model#set, -the core operation for updating the data contained by the collection.

    +

    Add a model, or list of models to the set. models may be Backbone +Models or raw JavaScript objects to be converted to Models, or any +combination of the two.

    -
        set: function(models, options) {
    -      options = _.defaults({}, options, setOptions);
    -      if (options.parse) models = this.parse(models, options);
    -      var singular = !_.isArray(models);
    -      models = singular ? (models ? [models] : []) : models.slice();
    -      var id, model, attrs, existing, sort;
    -      var at = options.at;
    -      if (at != null) at = +at;
    -      if (at < 0) at += this.length + 1;
    -      var sortable = this.comparator && (at == null) && options.sort !== false;
    -      var sortAttr = _.isString(this.comparator) ? this.comparator : null;
    -      var toAdd = [], toRemove = [], modelMap = {};
    -      var add = options.add, merge = options.merge, remove = options.remove;
    -      var order = !sortable && add && remove ? [] : false;
    -      var orderChanged = false;
    +
        add: function(models, options) {
    +      return this.set(models, _.extend({merge: false}, options, addOptions));
    +    },
    @@ -2135,13 +2135,21 @@ the core operation for updating the data contained by the collection.

    -

    Turn bare objects into model references, and prevent invalid models -from being added.

    +

    Remove a model, or a list of models from the set.

    -
          for (var i = 0; i < models.length; i++) {
    -        attrs = models[i];
    +
        remove: function(models, options) {
    +      options = _.extend({}, options);
    +      var singular = !_.isArray(models);
    +      models = singular ? [models] : models.slice();
    +      var removed = this._removeModels(models, options);
    +      if (!options.silent && removed.length) {
    +        options.changes = {added: [], merged: [], removed: removed};
    +        this.trigger('update', this, options);
    +      }
    +      return singular ? removed[0] : removed;
    +    },
    @@ -2152,20 +2160,42 @@ from being added.

    -

    If a duplicate is found, prevent it from being added and -optionally merge it into the existing model.

    +

    Update a collection by set-ing a new list of models, adding new ones, +removing models that are no longer present, and merging models that +already exist in the collection, as necessary. Similar to Model#set, +the core operation for updating the data contained by the collection.

    -
            if (existing = this.get(attrs)) {
    -          if (remove) modelMap[existing.cid] = true;
    -          if (merge && attrs !== existing) {
    -            attrs = this._isModel(attrs) ? attrs.attributes : attrs;
    -            if (options.parse) attrs = existing.parse(attrs, options);
    -            existing.set(attrs, options);
    -            if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
    -          }
    -          models[i] = existing;
    +
        set: function(models, options) {
    +      if (models == null) return;
    +
    +      options = _.extend({}, setOptions, options);
    +      if (options.parse && !this._isModel(models)) {
    +        models = this.parse(models, options) || [];
    +      }
    +
    +      var singular = !_.isArray(models);
    +      models = singular ? [models] : models.slice();
    +
    +      var at = options.at;
    +      if (at != null) at = +at;
    +      if (at > this.length) at = this.length;
    +      if (at < 0) at += this.length + 1;
    +
    +      var set = [];
    +      var toAdd = [];
    +      var toMerge = [];
    +      var toRemove = [];
    +      var modelMap = {};
    +
    +      var add = options.add;
    +      var merge = options.merge;
    +      var remove = options.remove;
    +
    +      var sort = false;
    +      var sortable = this.comparator && at == null && options.sort !== false;
    +      var sortAttr = _.isString(this.comparator) ? this.comparator : null;
    @@ -2176,16 +2206,14 @@ optionally merge it into the existing model.

    -

    If this is a new, valid model, push it to the toAdd list.

    +

    Turn bare objects into model references, and prevent invalid models +from being added.

    -
            } else if (add) {
    -          model = models[i] = this._prepareModel(attrs, options);
    -          if (!model) continue;
    -          toAdd.push(model);
    -          this._addReference(model, options);
    -        }
    +
          var model, i;
    +      for (i = 0; i < models.length; i++) {
    +        model = models[i];
    @@ -2196,15 +2224,25 @@ optionally merge it into the existing model.

    -

    Do not add multiple models with the same id.

    +

    If a duplicate is found, prevent it from being added and +optionally merge it into the existing model.

    -
            model = existing || model;
    -        if (!model) continue;
    -        id = this.modelId(model.attributes);
    -        if (order && (model.isNew() || !modelMap[id])) {
    -          order.push(model);
    +
            var existing = this.get(model);
    +        if (existing) {
    +          if (merge && model !== existing) {
    +            var attrs = this._isModel(model) ? model.attributes : model;
    +            if (options.parse) attrs = existing.parse(attrs, options);
    +            existing.set(attrs, options);
    +            toMerge.push(existing);
    +            if (sortable && !sort) sort = existing.hasChanged(sortAttr);
    +          }
    +          if (!modelMap[existing.cid]) {
    +            modelMap[existing.cid] = true;
    +            set.push(existing);
    +          }
    +          models[i] = existing;
    @@ -2215,14 +2253,19 @@ optionally merge it into the existing model.

    -

    Check to see if this is actually a new model at this index.

    +

    If this is a new, valid model, push it to the toAdd list.

    -
              orderChanged = orderChanged || !this.models[i] || model.cid !== this.models[i].cid;
    +            
            } else if (add) {
    +          model = models[i] = this._prepareModel(model, options);
    +          if (model) {
    +            toAdd.push(model);
    +            this._addReference(model, options);
    +            modelMap[model.cid] = true;
    +            set.push(model);
    +          }
             }
    -
    -        modelMap[id] = true;
           }
    @@ -2234,13 +2277,14 @@ optionally merge it into the existing model.

    -

    Remove nonexistent models if appropriate.

    +

    Remove stale models.

          if (remove) {
    -        for (var i = 0; i < this.length; i++) {
    -          if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
    +        for (i = 0; i < this.length; i++) {
    +          model = this.models[i];
    +          if (!modelMap[model.cid]) toRemove.push(model);
             }
             if (toRemove.length) this._removeModels(toRemove, options);
           }
    @@ -2258,20 +2302,19 @@ optionally merge it into the existing model.

    -
          if (toAdd.length || orderChanged) {
    +            
          var orderChanged = false;
    +      var replace = !sortable && add && remove;
    +      if (set.length && replace) {
    +        orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
    +          return m !== set[index];
    +        });
    +        this.models.length = 0;
    +        splice(this.models, set, 0);
    +        this.length = this.models.length;
    +      } else if (toAdd.length) {
             if (sortable) sort = true;
    -        this.length += toAdd.length;
    -        if (at != null) {
    -          for (var i = 0; i < toAdd.length; i++) {
    -            this.models.splice(at + i, 0, toAdd[i]);
    -          }
    -        } else {
    -          if (order) this.models.length = 0;
    -          var orderedModels = order || toAdd;
    -          for (var i = 0; i < orderedModels.length; i++) {
    -            this.models.push(orderedModels[i]);
    -          }
    -        }
    +        splice(this.models, toAdd, at == null ? this.length : at);
    +        this.length = this.models.length;
           }
    @@ -2298,18 +2341,25 @@ optionally merge it into the existing model.

    -

    Unless silenced, it’s time to fire all appropriate add/sort events.

    +

    Unless silenced, it’s time to fire all appropriate add/sort/update events.

          if (!options.silent) {
    -        var addOpts = at != null ? _.clone(options) : options;
    -        for (var i = 0; i < toAdd.length; i++) {
    -          if (at != null) addOpts.index = at + i;
    -          (model = toAdd[i]).trigger('add', model, this, addOpts);
    +        for (i = 0; i < toAdd.length; i++) {
    +          if (at != null) options.index = at + i;
    +          model = toAdd[i];
    +          model.trigger('add', model, this, options);
             }
             if (sort || orderChanged) this.trigger('sort', this, options);
    -        if (toAdd.length || toRemove.length) this.trigger('update', this, options);
    +        if (toAdd.length || toRemove.length || toMerge.length) {
    +          options.changes = {
    +            added: toAdd,
    +            removed: toRemove,
    +            merged: toMerge
    +          };
    +          this.trigger('update', this, options);
    +        }
           }
    @@ -2344,7 +2394,7 @@ Useful for bulk operations and optimizations.

    -
        reset: function(models, options) {
    +            
        reset: function(models, options) {
           options = options ? _.clone(options) : {};
           for (var i = 0; i < this.models.length; i++) {
             this._removeReference(this.models[i], options);
    @@ -2369,7 +2419,7 @@ Useful for bulk operations and optimizations.

    -
        push: function(model, options) {
    +            
        push: function(model, options) {
           return this.add(model, _.extend({at: this.length}, options));
         },
    @@ -2386,10 +2436,9 @@ Useful for bulk operations and optimizations.

    -
        pop: function(options) {
    +            
        pop: function(options) {
           var model = this.at(this.length - 1);
    -      this.remove(model, options);
    -      return model;
    +      return this.remove(model, options);
         },
    @@ -2405,7 +2454,7 @@ Useful for bulk operations and optimizations.

    -
        unshift: function(model, options) {
    +            
        unshift: function(model, options) {
           return this.add(model, _.extend({at: 0}, options));
         },
    @@ -2422,10 +2471,9 @@ Useful for bulk operations and optimizations.

    -
        shift: function(options) {
    +            
        shift: function(options) {
           var model = this.at(0);
    -      this.remove(model, options);
    -      return model;
    +      return this.remove(model, options);
         },
    @@ -2441,7 +2489,7 @@ Useful for bulk operations and optimizations.

    -
        slice: function() {
    +            
        slice: function() {
           return slice.apply(this.models, arguments);
         },
    @@ -2454,14 +2502,16 @@ Useful for bulk operations and optimizations.

    -

    Get a model from the set by id.

    +

    Get a model from the set by id, cid, model object with id or cid +properties, or an attributes object that is transformed through modelId.

    -
        get: function(obj) {
    +            
        get: function(obj) {
           if (obj == null) return void 0;
    -      var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
    -      return this._byId[obj] || this._byId[id] || this._byId[obj.cid];
    +      return this._byId[obj] ||
    +        this._byId[this.modelId(obj.attributes || obj)] ||
    +        obj.cid && this._byId[obj.cid];
         },
    @@ -2473,13 +2523,12 @@ Useful for bulk operations and optimizations.

    -

    Get the model at the given index.

    +

    Returns true if the model is in the collection.

    -
        at: function(index) {
    -      if (index < 0) index += this.length;
    -      return this.models[index];
    +            
        has: function(obj) {
    +      return this.get(obj) != null;
         },
    @@ -2491,16 +2540,13 @@ Useful for bulk operations and optimizations.

    -

    Return models with matching attributes. Useful for simple cases of -filter.

    +

    Get the model at the given index.

    -
        where: function(attrs, first) {
    -      var matches = _.matches(attrs);
    -      return this[first ? 'find' : 'filter'](function(model) {
    -        return matches(model.attributes);
    -      });
    +            
        at: function(index) {
    +      if (index < 0) index += this.length;
    +      return this.models[index];
         },
    @@ -2512,13 +2558,13 @@ Useful for bulk operations and optimizations.

    -

    Return the first model with matching attributes. Useful for simple cases -of find.

    +

    Return models with matching attributes. Useful for simple cases of +filter.

    -
        findWhere: function(attrs) {
    -      return this.where(attrs, true);
    +            
        where: function(attrs, first) {
    +      return this[first ? 'find' : 'filter'](attrs);
         },
    @@ -2530,15 +2576,14 @@ of find.

    -

    Force the collection to re-sort itself. You don’t need to call this under -normal circumstances, as the set will maintain sort order as each item -is added.

    +

    Return the first model with matching attributes. Useful for simple cases +of find.

    -
        sort: function(options) {
    -      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
    -      options || (options = {});
    +
        findWhere: function(attrs) {
    +      return this.where(attrs, true);
    +    },
    @@ -2549,19 +2594,19 @@ is added.

    -

    Run sort based on type of comparator.

    +

    Force the collection to re-sort itself. You don’t need to call this under +normal circumstances, as the set will maintain sort order as each item +is added.

    -
          if (_.isString(this.comparator) || this.comparator.length === 1) {
    -        this.models = this.sortBy(this.comparator, this);
    -      } else {
    -        this.models.sort(_.bind(this.comparator, this));
    -      }
    +            
        sort: function(options) {
    +      var comparator = this.comparator;
    +      if (!comparator) throw new Error('Cannot sort a set without a comparator');
    +      options || (options = {});
     
    -      if (!options.silent) this.trigger('sort', this, options);
    -      return this;
    -    },
    + var length = comparator.length; + if (_.isFunction(comparator)) comparator = _.bind(comparator, this);
    @@ -2572,12 +2617,17 @@ is added.

    -

    Pluck an attribute from each model in the collection.

    +

    Run sort based on type of comparator.

    -
        pluck: function(attr) {
    -      return _.invoke(this.models, 'get', attr);
    +            
          if (length === 1 || _.isString(comparator)) {
    +        this.models = this.sortBy(comparator);
    +      } else {
    +        this.models.sort(comparator);
    +      }
    +      if (!options.silent) this.trigger('sort', this, options);
    +      return this;
         },
    @@ -2589,18 +2639,34 @@ is added.

    +

    Pluck an attribute from each model in the collection.

    + +
    + +
        pluck: function(attr) {
    +      return this.map(attr + '');
    +    },
    + + + + +
  • +
    + +
    + +

    Fetch the default set of models for this collection, resetting the collection when they arrive. If reset: true is passed, the response data will be passed through the reset method instead of set.

    -
        fetch: function(options) {
    -      options = options ? _.clone(options) : {};
    -      if (options.parse === void 0) options.parse = true;
    +            
        fetch: function(options) {
    +      options = _.extend({parse: true}, options);
           var success = options.success;
           var collection = this;
    -      options.success = function(resp) {
    +      options.success = function(resp) {
             var method = options.reset ? 'reset' : 'set';
             collection[method](resp, options);
             if (success) success.call(options.context, collection, resp, options);
    @@ -2613,11 +2679,11 @@ data will be passed through the reset method instead of set
             
             
    -        
  • +
  • - +

    Create a new instance of a model in this collection. Add the model to the collection immediately, unless wait: true is passed, in which case we @@ -2625,16 +2691,17 @@ wait for the server to agree.

    -
        create: function(model, options) {
    +            
        create: function(model, options) {
           options = options ? _.clone(options) : {};
           var wait = options.wait;
    -      if (!(model = this._prepareModel(model, options))) return false;
    +      model = this._prepareModel(model, options);
    +      if (!model) return false;
           if (!wait) this.add(model, options);
           var collection = this;
           var success = options.success;
    -      options.success = function(model, resp, callbackOpts) {
    -        if (wait) collection.add(model, callbackOpts);
    -        if (success) success.call(callbackOpts.context, model, resp, callbackOpts);
    +      options.success = function(m, resp, callbackOpts) {
    +        if (wait) collection.add(m, callbackOpts);
    +        if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
           };
           model.save(null, options);
           return model;
    @@ -2643,39 +2710,19 @@ wait for the server to agree.

  • -
  • -
    - -
    - -
    -

    parse converts a response into a list of models to be added to the -collection. The default implementation is just to pass it through.

    - -
    - -
        parse: function(resp, options) {
    -      return resp;
    -    },
    - -
  • - -
  • -

    Create a new collection with an identical list of models as this one.

    +

    parse converts a response into a list of models to be added to the +collection. The default implementation is just to pass it through.

    -
        clone: function() {
    -      return new this.constructor(this.models, {
    -        model: this.model,
    -        comparator: this.comparator
    -      });
    +            
        parse: function(resp, options) {
    +      return resp;
         },
  • @@ -2687,12 +2734,15 @@ collection. The default implementation is just to pass it through.

    -

    Define how to uniquely identify models in the collection.

    +

    Create a new collection with an identical list of models as this one.

    -
        modelId: function (attrs) {
    -      return attrs[this.model.prototype.idAttribute || 'id'];
    +            
        clone: function() {
    +      return new this.constructor(this.models, {
    +        model: this.model,
    +        comparator: this.comparator
    +      });
         },
  • @@ -2704,15 +2754,12 @@ collection. The default implementation is just to pass it through.

    -

    Private method to reset all internal state. Called when the collection -is first initialized or reset.

    +

    Define how to uniquely identify models in the collection.

    -
        _reset: function() {
    -      this.length = 0;
    -      this.models = [];
    -      this._byId  = {};
    +            
        modelId: function(attrs) {
    +      return attrs[this.model.prototype.idAttribute || 'id'];
         },
    @@ -2724,12 +2771,32 @@ is first initialized or reset.

    +

    Private method to reset all internal state. Called when the collection +is first initialized or reset.

    + +
    + +
        _reset: function() {
    +      this.length = 0;
    +      this.models = [];
    +      this._byId  = {};
    +    },
    + + + + +
  • +
    + +
    + +

    Prepare a hash of attributes (or other model) to be added to this collection.

    -
        _prepareModel: function(attrs, options) {
    +            
        _prepareModel: function(attrs, options) {
           if (this._isModel(attrs)) {
             if (!attrs.collection) attrs.collection = this;
             return attrs;
    @@ -2745,54 +2812,25 @@ collection.

  • -
  • -
    - -
    - -
    -

    Internal method called by both remove and set. Does not trigger any -additional events. Returns true if anything was actually removed.

    - -
    - -
        _removeModels: function(models, options) {
    -      var i, l, index, model, removed = false;
    -      for (var i = 0, j = 0; i < models.length; i++) {
    -        var model = models[i] = this.get(models[i]);
    -        if (!model) continue;
    -        var id = this.modelId(model.attributes);
    -        if (id != null) delete this._byId[id];
    -        delete this._byId[model.cid];
    -        var index = this.indexOf(model);
    -        this.models.splice(index, 1);
    -        this.length--;
    -        if (!options.silent) {
    -          options.index = index;
    -          model.trigger('remove', model, this, options);
    -        }
    -        models[j++] = model;
    -        this._removeReference(model, options);
    -        removed = true;
    -      }
    - -
  • - -
  • -

    We only need to slice if models array should be smaller, which is -caused by some models not actually getting removed.

    +

    Internal method called by both remove and set.

    -
          if (models.length !== j) models = models.slice(0, j);
    -      return removed;
    -    },
    +
        _removeModels: function(models, options) {
    +      var removed = [];
    +      for (var i = 0; i < models.length; i++) {
    +        var model = this.get(models[i]);
    +        if (!model) continue;
    +
    +        var index = this.indexOf(model);
    +        this.models.splice(index, 1);
    +        this.length--;
  • @@ -2803,13 +2841,24 @@ caused by some models not actually getting removed.

    -

    Method for checking whether an object should be considered a model for -the purposes of adding to the collection.

    +

    Remove references before triggering ‘remove’ event to prevent an +infinite loop. #3693

    -
        _isModel: function (model) {
    -      return model instanceof Model;
    +            
            delete this._byId[model.cid];
    +        var id = this.modelId(model.attributes);
    +        if (id != null) delete this._byId[id];
    +
    +        if (!options.silent) {
    +          options.index = index;
    +          model.trigger('remove', model, this, options);
    +        }
    +
    +        removed.push(model);
    +        this._removeReference(model, options);
    +      }
    +      return removed;
         },
    @@ -2821,15 +2870,13 @@ the purposes of adding to the collection.

    -

    Internal method to create a model’s ties to a collection.

    +

    Method for checking whether an object should be considered a model for +the purposes of adding to the collection.

    -
        _addReference: function(model, options) {
    -      this._byId[model.cid] = model;
    -      var id = this.modelId(model.attributes);
    -      if (id != null) this._byId[id] = model;
    -      model.on('all', this._onModelEvent, this);
    +            
        _isModel: function(model) {
    +      return model instanceof Model;
         },
    @@ -2841,13 +2888,15 @@ the purposes of adding to the collection.

    -

    Internal method to sever a model’s ties to a collection.

    +

    Internal method to create a model’s ties to a collection.

    -
        _removeReference: function(model, options) {
    -      if (this === model.collection) delete model.collection;
    -      model.off('all', this._onModelEvent, this);
    +            
        _addReference: function(model, options) {
    +      this._byId[model.cid] = model;
    +      var id = this.modelId(model.attributes);
    +      if (id != null) this._byId[id] = model;
    +      model.on('all', this._onModelEvent, this);
         },
    @@ -2859,28 +2908,17 @@ the purposes of adding to the collection.

    -

    Internal method called every time a model in the set fires an event. -Sets need to update their indexes when models change ids. All other -events simply proxy through. “add” and “remove” events that originate -in other collections are ignored.

    +

    Internal method to sever a model’s ties to a collection.

    -
        _onModelEvent: function(event, model, collection, options) {
    -      if ((event === 'add' || event === 'remove') && collection !== this) return;
    -      if (event === 'destroy') this.remove(model, options);
    -      if (event === 'change') {
    -        var prevId = this.modelId(model.previousAttributes());
    -        var id = this.modelId(model.attributes);
    -        if (prevId !== id) {
    -          if (prevId != null) delete this._byId[prevId];
    -          if (id != null) this._byId[id] = model;
    -        }
    -      }
    -      this.trigger.apply(this, arguments);
    -    }
    -
    -  });
    +
        _removeReference: function(model, options) {
    +      delete this._byId[model.cid];
    +      var id = this.modelId(model.attributes);
    +      if (id != null) delete this._byId[id];
    +      if (this === model.collection) delete model.collection;
    +      model.off('all', this._onModelEvent, this);
    +    },
    @@ -2891,19 +2929,30 @@ in other collections are ignored.

    -

    Underscore methods that we want to implement on the Collection. -90% of the core usefulness of Backbone Collections is actually implemented -right here:

    +

    Internal method called every time a model in the set fires an event. +Sets need to update their indexes when models change ids. All other +events simply proxy through. “add” and “remove” events that originate +in other collections are ignored.

    -
      var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4,
    -      foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3,
    -      select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 2,
    -      contains: 2, invoke: 2, max: 3, min: 3, toArray: 1, size: 1, first: 3,
    -      head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
    -      without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
    -      isEmpty: 1, chain: 1, sample: 3, partition: 3 };
    +
        _onModelEvent: function(event, model, collection, options) {
    +      if (model) {
    +        if ((event === 'add' || event === 'remove') && collection !== this) return;
    +        if (event === 'destroy') this.remove(model, options);
    +        if (event === 'change') {
    +          var prevId = this.modelId(model.previousAttributes());
    +          var id = this.modelId(model.attributes);
    +          if (prevId !== id) {
    +            if (prevId != null) delete this._byId[prevId];
    +            if (id != null) this._byId[id] = model;
    +          }
    +        }
    +      }
    +      this.trigger.apply(this, arguments);
    +    }
    +
    +  });
    @@ -2914,11 +2963,20 @@ right here:

    -

    Mix in each Underscore method as a proxy to Collection#models.

    +

    Underscore methods that we want to implement on the Collection. +90% of the core usefulness of Backbone Collections is actually implemented +right here:

    -
      addUnderscoreMethods(Collection, collectionMethods, 'models');
    +
      var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
    +      foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
    +      select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
    +      contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
    +      head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
    +      without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
    +      isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
    +      sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};
    @@ -2929,11 +2987,11 @@ right here:

    -

    Underscore methods that take a property name as an argument.

    +

    Mix in each Underscore method as a proxy to Collection#models.

    -
      var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
    +
      addUnderscoreMethods(Collection, collectionMethods, 'models');
    @@ -2944,20 +3002,10 @@ right here:

    -

    Use attributes instead of properties.

    +

    Backbone.View

    -
      _.each(attributeMethods, function(method) {
    -    if (!_[method]) return;
    -    Collection.prototype[method] = function(value, context) {
    -      var iterator = _.isFunction(value) ? value : function(model) {
    -        return model.get(value);
    -      };
    -      return _[method](this.models, iterator, context);
    -    };
    -  });
    - @@ -2967,8 +3015,7 @@ right here:

    -

    Backbone.View

    - +
    @@ -2980,18 +3027,6 @@ right here:

    - -
    - - - - -
  • -
    - -
    - -

    Backbone Views are almost more convention than they are actual code. A View is simply a JavaScript object that represents a logical chunk of UI in the DOM. This might be a single item, an entire list, a sidebar or panel, or @@ -3005,20 +3040,19 @@ react to specific changes in the state of your models.

  • -
  • +
  • - +

    Creating a Backbone.View creates its initial element outside of the DOM, if an existing element is not provided…

    -
      var View = Backbone.View = function(options) {
    +            
      var View = Backbone.View = function(options) {
         this.cid = _.uniqueId('view');
    -    options || (options = {});
         _.extend(this, _.pick(options, viewOptions));
         this._ensureElement();
         this.initialize.apply(this, arguments);
    @@ -3027,11 +3061,11 @@ if an existing element is not provided…

  • -
  • +
  • - +

    Cached regex to split keys for delegate.

    @@ -3042,13 +3076,13 @@ if an existing element is not provided…

  • -
  • +
  • - +
    -

    List of view options to be merged as properties.

    +

    List of view options to be set as properties.

    @@ -3057,11 +3091,11 @@ if an existing element is not provided…

  • -
  • +
  • - +

    Set up all inheritable Backbone.View properties and methods.

    @@ -3072,11 +3106,11 @@ if an existing element is not provided…

  • -
  • +
  • - +

    The default tagName of a View’s element is "div".

    @@ -3087,36 +3121,55 @@ if an existing element is not provided…

  • -
  • +
  • - +

    jQuery delegate for element lookup, scoped to DOM elements within the current view. This should be preferred to global lookups where possible.

    -
        $: function(selector) {
    +            
        $: function(selector) {
           return this.$el.find(selector);
         },
  • +
  • +
    + +
    + +
    +

    Initialize is an empty function by default. Override it with your own +initialization logic.

    + +
    + +
        initialize: function(){},
    + +
  • + +
  • -

    Initialize is an empty function by default. Override it with your own -initialization logic.

    +

    render is the core function that your view should override, in order +to populate its element (this.el), with the appropriate HTML. The +convention is for render to always return this.

    -
        initialize: function(){},
    +
        render: function() {
    +      return this;
    +    },
  • @@ -3127,13 +3180,14 @@ initialization logic.

    -

    render is the core function that your view should override, in order -to populate its element (this.el), with the appropriate HTML. The -convention is for render to always return this.

    +

    Remove this view by taking the element out of the DOM, and removing any +applicable Backbone.Events listeners.

    -
        render: function() {
    +            
        remove: function() {
    +      this._removeElement();
    +      this.stopListening();
           return this;
         },
    @@ -3146,15 +3200,14 @@ convention is for render to always return this.

    -

    Remove this view by taking the element out of the DOM, and removing any -applicable Backbone.Events listeners.

    +

    Remove this view’s element from the document and all event listeners +attached to it. Exposed for subclasses using an alternative DOM +manipulation API.

    -
        remove: function() {
    -      this._removeElement();
    -      this.stopListening();
    -      return this;
    +            
        _removeElement: function() {
    +      this.$el.remove();
         },
    @@ -3166,14 +3219,16 @@ applicable Backbone.Events listeners.

    -

    Remove this view’s element from the document and all event listeners -attached to it. Exposed for subclasses using an alternative DOM -manipulation API.

    +

    Change the view’s element (this.el property) and re-delegate the +view’s events on the new element.

    -
        _removeElement: function() {
    -      this.$el.remove();
    +            
        setElement: function(element) {
    +      this.undelegateEvents();
    +      this._setElement(element);
    +      this.delegateEvents();
    +      return this;
         },
    @@ -3185,16 +3240,17 @@ manipulation API.

    -

    Change the view’s element (this.el property) and re-delegate the -view’s events on the new element.

    +

    Creates the this.el and this.$el references for this view using the +given el. el can be a CSS selector or an HTML string, a jQuery +context or an element. Subclasses can override this to utilize an +alternative DOM manipulation API and are only required to set the +this.el property.

    -
        setElement: function(element) {
    -      this.undelegateEvents();
    -      this._setElement(element);
    -      this.delegateEvents();
    -      return this;
    +            
        _setElement: function(el) {
    +      this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
    +      this.el = this.$el[0];
         },
    @@ -3206,17 +3262,31 @@ view’s events on the new element.

    -

    Creates the this.el and this.$el references for this view using the -given el. el can be a CSS selector or an HTML string, a jQuery -context or an element. Subclasses can override this to utilize an -alternative DOM manipulation API and are only required to set the -this.el property.

    +

    Set callbacks, where this.events is a hash of

    +

    {“event selector”: “callback”}

    +
    {
    +  'mousedown .title':  'edit',
    +  'click .button':     'save',
    +  'click .open':       function(e) { ... }
    +}
    +

    pairs. Callbacks will be bound to the view, with this set properly. +Uses event delegation for efficiency. +Omitting the selector binds the event to this.el.

    -
        _setElement: function(el) {
    -      this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
    -      this.el = this.$el[0];
    +            
        delegateEvents: function(events) {
    +      events || (events = _.result(this, 'events'));
    +      if (!events) return this;
    +      this.undelegateEvents();
    +      for (var key in events) {
    +        var method = events[key];
    +        if (!_.isFunction(method)) method = this[method];
    +        if (!method) continue;
    +        var match = key.match(delegateEventSplitter);
    +        this.delegate(match[1], match[2], _.bind(method, this));
    +      }
    +      return this;
         },
    @@ -3228,29 +3298,14 @@ alternative DOM manipulation API and are only required to set the
    -

    Set callbacks, where this.events is a hash of

    -

    {“event selector”: “callback”}

    -
    {
    -  'mousedown .title':  'edit',
    -  'click .button':     'save',
    -  'click .open':       function(e) { ... }
    -}
    -

    pairs. Callbacks will be bound to the view, with this set properly. -Uses event delegation for efficiency. -Omitting the selector binds the event to this.el.

    +

    Add a single event listener to the view’s element (or a child element +using selector). This only works for delegate-able events: not focus, +blur, and not change, submit, and reset in Internet Explorer.

    -
        delegateEvents: function(events) {
    -      if (!(events || (events = _.result(this, 'events')))) return this;
    -      this.undelegateEvents();
    -      for (var key in events) {
    -        var method = events[key];
    -        if (!_.isFunction(method)) method = this[events[key]];
    -        if (!method) continue;
    -        var match = key.match(delegateEventSplitter);
    -        this.delegate(match[1], match[2], _.bind(method, this));
    -      }
    +            
        delegate: function(eventName, selector, listener) {
    +      this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
           return this;
         },
    @@ -3263,14 +3318,15 @@ Omitting the selector binds the event to this.el.

    -

    Add a single event listener to the view’s element (or a child element -using selector). This only works for delegate-able events: not focus, -blur, and not change, submit, and reset in Internet Explorer.

    +

    Clears all callbacks previously bound to the view by delegateEvents. +You usually don’t need to use this, but may wish to if you have multiple +Backbone views attached to the same DOM element.

    -
        delegate: function(eventName, selector, listener) {
    -      this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
    +            
        undelegateEvents: function() {
    +      if (this.$el) this.$el.off('.delegateEvents' + this.cid);
    +      return this;
         },
    @@ -3282,14 +3338,13 @@ using selector). This only works for delegate-able events: not
    -

    Clears all callbacks previously bound to the view by delegateEvents. -You usually don’t need to use this, but may wish to if you have multiple -Backbone views attached to the same DOM element.

    +

    A finer-grained undelegateEvents for removing a single delegated event. +selector and listener are both optional.

    -
        undelegateEvents: function() {
    -      if (this.$el) this.$el.off('.delegateEvents' + this.cid);
    +            
        undelegate: function(eventName, selector, listener) {
    +      this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
           return this;
         },
    @@ -3302,13 +3357,13 @@ Backbone views attached to the same DOM element.

    -

    A finer-grained undelegateEvents for removing a single delegated event. -selector and listener are both optional.

    +

    Produces a DOM element to be assigned to your view. Exposed for +subclasses using an alternative DOM manipulation API.

    -
        undelegate: function(eventName, selector, listener) {
    -      this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
    +            
        _createElement: function(tagName) {
    +      return document.createElement(tagName);
         },
    @@ -3320,24 +3375,6 @@ Backbone views attached to the same DOM element.

    -

    Produces a DOM element to be assigned to your view. Exposed for -subclasses using an alternative DOM manipulation API.

    - -
    - -
        _createElement: function(tagName) {
    -      return document.createElement(tagName);
    -    },
    - - - - -
  • -
    - -
    - -

    Ensure that the View has a DOM element to render into. If this.el is a string, pass it through $(), take the first matching element, and re-assign it to el. Otherwise, create @@ -3345,7 +3382,7 @@ an element from the id, className and tagName -

        _ensureElement: function() {
    +            
        _ensureElement: function() {
           if (!this.el) {
             var attrs = _.extend({}, _.result(this, 'attributes'));
             if (this.id) attrs.id = _.result(this, 'id');
    @@ -3360,18 +3397,18 @@ an element from the id, className and tagName
             
             
    -        
  • +
  • - +

    Set attributes from a hash on this view’s element. Exposed for subclasses using an alternative DOM manipulation API.

    -
        _setAttributes: function(attributes) {
    +            
        _setAttributes: function(attributes) {
           this.$el.attr(attributes);
         }
     
    @@ -3380,14 +3417,26 @@ subclasses using an alternative DOM manipulation API.

  • +
  • +
    + +
    + +
    +

    Backbone.sync

    + +
    + +
  • + +
  • -

    Backbone.sync

    - +
  • @@ -3399,18 +3448,6 @@ subclasses using an alternative DOM manipulation API.

    - -
    - -
  • - - -
  • -
    - -
    - -

    Override this function to change the manner in which Backbone persists models to the server. You will be passed the type of request, and the model in question. By default, makes a RESTful Ajax request @@ -3429,17 +3466,17 @@ it difficult to read the body of PUT requests.

    -
      Backbone.sync = function(method, model, options) {
    +            
      Backbone.sync = function(method, model, options) {
         var type = methodMap[method];
  • -
  • +
  • - +

    Default options, unless specified.

    @@ -3453,11 +3490,11 @@ it difficult to read the body of PUT requests.

  • -
  • +
  • - +

    Default JSON-request options.

    @@ -3468,11 +3505,11 @@ it difficult to read the body of PUT requests.

  • -
  • +
  • - +

    Ensure that we have a URL.

    @@ -3485,11 +3522,11 @@ it difficult to read the body of PUT requests.

  • -
  • +
  • - +

    Ensure that we have the appropriate request data.

    @@ -3503,11 +3540,11 @@ it difficult to read the body of PUT requests.

  • -
  • +
  • - +

    For older servers, emulate JSON by encoding the request into an HTML-form.

    @@ -3521,11 +3558,11 @@ it difficult to read the body of PUT requests.

  • -
  • +
  • - +

    For older servers, emulate HTTP by mimicking the HTTP method with _method And an X-HTTP-Method-Override header.

    @@ -3536,7 +3573,7 @@ And an X-HTTP-Method-Override header.

    params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; - options.beforeSend = function(xhr) { + options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; @@ -3545,11 +3582,11 @@ And an X-HTTP-Method-Override header.

  • -
  • +
  • - +

    Don’t process data on a non-GET request.

    @@ -3562,18 +3599,18 @@ And an X-HTTP-Method-Override header.

  • -
  • +
  • - +

    Pass along textStatus and errorThrown from jQuery.

        var error = options.error;
    -    options.error = function(xhr, textStatus, errorThrown) {
    +    options.error = function(xhr, textStatus, errorThrown) {
           options.textStatus = textStatus;
           options.errorThrown = errorThrown;
           if (error) error.call(options.context, xhr, textStatus, errorThrown);
    @@ -3582,11 +3619,11 @@ And an X-HTTP-Method-Override header.

  • -
  • +
  • - +

    Make the request, allowing the user to override any Ajax options.

    @@ -3600,11 +3637,11 @@ And an X-HTTP-Method-Override header.

  • -
  • +
  • - +

    Map from CRUD to HTTP for our default Backbone.sync implementation.

    @@ -3613,9 +3650,27 @@ And an X-HTTP-Method-Override header.

      var methodMap = {
         'create': 'POST',
         'update': 'PUT',
    -    'patch':  'PATCH',
    +    'patch': 'PATCH',
         'delete': 'DELETE',
    -    'read':   'GET'
    +    'read': 'GET'
    +  };
    + +
  • + + +
  • +
    + +
    + +
    +

    Set the default implementation of Backbone.ajax to proxy through to $. +Override this if you’d like to use a different library.

    + +
    + +
      Backbone.ajax = function() {
    +    return Backbone.$.ajax.apply(Backbone.$, arguments);
       };
  • @@ -3627,15 +3682,10 @@ And an X-HTTP-Method-Override header.

    -

    Set the default implementation of Backbone.ajax to proxy through to $. -Override this if you’d like to use a different library.

    +

    Backbone.Router

    -
      Backbone.ajax = function() {
    -    return Backbone.$.ajax.apply(Backbone.$, arguments);
    -  };
    - @@ -3645,8 +3695,7 @@ Override this if you’d like to use a different library.

    -

    Backbone.Router

    - +
    @@ -3658,24 +3707,12 @@ Override this if you’d like to use a different library.

    - -
    - - - - -
  • -
    - -
    - -

    Routers map faux-URLs to actions, and fire events when routes are matched. Creating a new one sets its routes hash, if not set statically.

    -
      var Router = Backbone.Router = function(options) {
    +            
      var Router = Backbone.Router = function(options) {
         options || (options = {});
         if (options.routes) this.routes = options.routes;
         this._bindRoutes();
    @@ -3685,11 +3722,11 @@ matched. Creating a new one sets its routes hash, if not set static
             
  • -
  • +
  • - +

    Cached regular expressions for matching named param parts and splatted parts of route strings.

    @@ -3704,11 +3741,11 @@ parts of route strings.

  • -
  • +
  • - +

    Set up all inheritable Backbone.Router properties and methods.

    @@ -3719,36 +3756,36 @@ parts of route strings.

  • -
  • +
  • - +

    Initialize is an empty function by default. Override it with your own initialization logic.

    -
        initialize: function(){},
    +
        initialize: function(){},
  • -
  • +
  • - +

    Manually bind a single named route to a callback. For example:

    -
    this.route('search/:query/p:num', 'search', function(query, num) {
    +
    this.route('search/:query/p:num', 'search', function(query, num) {
       ...
     });
     
    -
        route: function(route, name, callback) {
    +            
        route: function(route, name, callback) {
           if (!_.isRegExp(route)) route = this._routeToRegExp(route);
           if (_.isFunction(name)) {
             callback = name;
    @@ -3756,7 +3793,7 @@ initialization logic.

    } if (!callback) callback = this[name]; var router = this; - Backbone.history.route(route, function(fragment) { + Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); if (router.execute(callback, args, name) !== false) { router.trigger.apply(router, ['route:' + name].concat(args)); @@ -3770,55 +3807,55 @@ initialization logic.

  • -
  • +
  • - +

    Execute a route handler with the provided parameters. This is an excellent place to do pre-route setup or post-route cleanup.

    -
        execute: function(callback, args, name) {
    +            
        execute: function(callback, args, name) {
           if (callback) callback.apply(this, args);
         },
  • +
  • +
    + +
    + +
    +

    Simple proxy to Backbone.history to save a fragment into the history.

    + +
    + +
        navigate: function(fragment, options) {
    +      Backbone.history.navigate(fragment, options);
    +      return this;
    +    },
    + +
  • + +
  • -

    Simple proxy to Backbone.history to save a fragment into the history.

    - -
    - -
        navigate: function(fragment, options) {
    -      Backbone.history.navigate(fragment, options);
    -      return this;
    -    },
    - -
  • - - -
  • -
    - -
    - -

    Bind all defined routes to Backbone.history. We have to reverse the order of the routes here to support behavior where the most general routes can be defined at the bottom of the route map.

    -
        _bindRoutes: function() {
    +            
        _bindRoutes: function() {
           if (!this.routes) return;
           this.routes = _.result(this, 'routes');
           var route, routes = _.keys(this.routes);
    @@ -3830,21 +3867,21 @@ routes can be defined at the bottom of the route map.

  • -
  • +
  • - +

    Convert a route string into a regular expression, suitable for matching against the current location hash.

    -
        _routeToRegExp: function(route) {
    +            
        _routeToRegExp: function(route) {
           route = route.replace(escapeRegExp, '\\$&')
                        .replace(optionalParam, '(?:$1)?')
    -                   .replace(namedParam, function(match, optional) {
    +                   .replace(namedParam, function(match, optional) {
                          return optional ? match : '([^/?]+)';
                        })
                        .replace(splatParam, '([^?]*?)');
    @@ -3854,11 +3891,11 @@ against the current location hash.

  • -
  • +
  • - +

    Given a route, and a URL fragment that it matches, return the array of extracted decoded parameters. Empty or unmatched parameters will be @@ -3866,18 +3903,18 @@ treated as null to normalize cross-browser behavior.

    -
        _extractParameters: function(route, fragment) {
    +            
        _extractParameters: function(route, fragment) {
           var params = route.exec(fragment).slice(1);
    -      return _.map(params, function(param, i) {
    + return _.map(params, function(param, i) {
  • -
  • +
  • - +

    Don’t decode the search params.

    @@ -3893,14 +3930,26 @@ treated as null to normalize cross-browser behavior.

  • +
  • +
    + +
    + +
    +

    Backbone.History

    + +
    + +
  • + +
  • -

    Backbone.History

    - +
  • @@ -3912,9 +3961,18 @@ treated as null to normalize cross-browser behavior.

    - +

    Handles cross-browser history management, based on either +pushState and real URLs, or +onhashchange +and URL fragments. If the browser supports neither (old IE, natch), +falls back to polling.

    +
    +
      var History = Backbone.History = function() {
    +    this.handlers = [];
    +    this.checkUrl = _.bind(this.checkUrl, this);
    + @@ -3924,27 +3982,6 @@ treated as null to normalize cross-browser behavior.

    -

    Handles cross-browser history management, based on either -pushState and real URLs, or -onhashchange -and URL fragments. If the browser supports neither (old IE, natch), -falls back to polling.

    - -
    - -
      var History = Backbone.History = function() {
    -    this.handlers = [];
    -    _.bindAll(this, 'checkUrl');
    - - - - -
  • -
    - -
    - -

    Ensure that History can be used outside of the browser.

    @@ -3958,11 +3995,11 @@ falls back to polling.

  • -
  • +
  • - +

    Cached regex for stripping a leading hash/slash and trailing space.

    @@ -3973,11 +4010,11 @@ falls back to polling.

  • -
  • +
  • - +

    Cached regex for stripping leading and trailing slashes.

    @@ -3988,11 +4025,11 @@ falls back to polling.

  • -
  • +
  • - +

    Cached regex for stripping urls of hash.

    @@ -4003,11 +4040,11 @@ falls back to polling.

  • -
  • +
  • - +

    Has the history handling already been started?

    @@ -4018,11 +4055,11 @@ falls back to polling.

  • -
  • +
  • - +

    Set up all inheritable Backbone.History properties and methods.

    @@ -4033,11 +4070,11 @@ falls back to polling.

  • -
  • +
  • - +

    The default interval to poll for hash changes, if necessary, is twenty times a second.

    @@ -4049,19 +4086,38 @@ twenty times a second.

  • +
  • +
    + +
    + +
    +

    Are we at the app root?

    + +
    + +
        atRoot: function() {
    +      var path = this.location.pathname.replace(/[^\/]$/, '$&/');
    +      return path === this.root && !this.getSearch();
    +    },
    + +
  • + +
  • -

    Are we at the app root?

    +

    Does the pathname match the root?

    -
        atRoot: function() {
    -      var path = this.location.pathname.replace(/[^\/]$/, '$&/');
    -      return path === this.root && !this.getSearch();
    +            
        matchRoot: function() {
    +      var path = this.decodeFragment(this.location.pathname);
    +      var rootPath = path.slice(0, this.root.length - 1) + '/';
    +      return rootPath === this.root;
         },
  • @@ -4073,14 +4129,14 @@ twenty times a second.

    -

    Does the pathname match the root?

    +

    Unicode characters in location.pathname are percent encoded so they’re +decoded for comparison. %25 should not be decoded since it may be part +of an encoded parameter.

    -
        matchRoot: function() {
    -      var path = this.decodeFragment(this.location.pathname);
    -      var root = path.slice(0, this.root.length - 1) + '/';
    -      return root === this.root;
    +            
        decodeFragment: function(fragment) {
    +      return decodeURI(fragment.replace(/%25/g, '%2525'));
         },
    @@ -4092,14 +4148,14 @@ twenty times a second.

    -

    Unicode characters in location.pathname are percent encoded so they’re -decoded for comparison. %25 should not be decoded since it may be part -of an encoded parameter.

    +

    In IE6, the hash fragment and search params are incorrect if the +fragment contains ?.

    -
        decodeFragment: function(fragment) {
    -      return decodeURI(fragment.replace(/%25/g, '%2525'));
    +            
        getSearch: function() {
    +      var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
    +      return match ? match[0] : '';
         },
    @@ -4111,14 +4167,14 @@ of an encoded parameter.

    -

    In IE6, the hash fragment and search params are incorrect if the -fragment contains ?.

    +

    Gets the true hash value. Cannot use location.hash directly due to bug +in Firefox where location.hash will always be decoded.

    -
        getSearch: function() {
    -      var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
    -      return match ? match[0] : '';
    +            
        getHash: function(window) {
    +      var match = (window || this).location.href.match(/#(.*)$/);
    +      return match ? match[1] : '';
         },
    @@ -4130,14 +4186,15 @@ fragment contains ?.

    -

    Gets the true hash value. Cannot use location.hash directly due to bug -in Firefox where location.hash will always be decoded.

    +

    Get the pathname and search params, without the root.

    -
        getHash: function(window) {
    -      var match = (window || this).location.href.match(/#(.*)$/);
    -      return match ? match[1] : '';
    +            
        getPath: function() {
    +      var path = this.decodeFragment(
    +        this.location.pathname + this.getSearch()
    +      ).slice(this.root.length - 1);
    +      return path.charAt(0) === '/' ? path.slice(1) : path;
         },
    @@ -4149,31 +4206,11 @@ in Firefox where location.hash will always be decoded.

    -

    Get the pathname and search params, without the root.

    - -
    - -
        getPath: function() {
    -      var path = this.decodeFragment(
    -        this.location.pathname + this.getSearch()
    -      ).slice(this.root.length - 1);
    -      return path.charAt(0) === '/' ? path.slice(1) : path;
    -    },
    - - - - -
  • -
    - -
    - -

    Get the cross-browser normalized URL fragment from the path or hash.

    -
        getFragment: function(fragment) {
    +            
        getFragment: function(fragment) {
           if (fragment == null) {
             if (this._usePushState || !this._wantsHashChange) {
               fragment = this.getPath();
    @@ -4187,54 +4224,54 @@ in Firefox where location.hash will always be decoded.

  • -
  • +
  • - +

    Start the hash change handling, returning true if the current URL matches an existing route, and false otherwise.

    -
        start: function(options) {
    +            
        start: function(options) {
           if (History.started) throw new Error('Backbone.history has already been started');
           History.started = true;
  • +
  • +
    + +
    + +
    +

    Figure out the initial configuration. Do we need an iframe? +Is pushState desired … is it available?

    + +
    + +
          this.options          = _.extend({root: '/'}, this.options, options);
    +      this.root             = this.options.root;
    +      this._wantsHashChange = this.options.hashChange !== false;
    +      this._hasHashChange   = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
    +      this._useHashChange   = this._wantsHashChange && this._hasHashChange;
    +      this._wantsPushState  = !!this.options.pushState;
    +      this._hasPushState    = !!(this.history && this.history.pushState);
    +      this._usePushState    = this._wantsPushState && this._hasPushState;
    +      this.fragment         = this.getFragment();
    + +
  • + +
  • -

    Figure out the initial configuration. Do we need an iframe? -Is pushState desired … is it available?

    - -
    - -
          this.options          = _.extend({root: '/'}, this.options, options);
    -      this.root             = this.options.root;
    -      this._wantsHashChange = this.options.hashChange !== false;
    -      this._hasHashChange   = 'onhashchange' in window;
    -      this._useHashChange   = this._wantsHashChange && this._hasHashChange;
    -      this._wantsPushState  = !!this.options.pushState;
    -      this._hasPushState    = !!(this.history && this.history.pushState);
    -      this._usePushState    = this._wantsPushState && this._hasPushState;
    -      this.fragment         = this.getFragment();
    - -
  • - - -
  • -
    - -
    - -

    Normalize root to always include a leading and trailing slash.

    @@ -4244,11 +4281,11 @@ Is pushState desired … is it available?

  • -
  • +
  • - +

    Transition from hashChange to pushState or vice versa if both are requested.

    @@ -4260,11 +4297,11 @@ requested.

  • -
  • +
  • - +

    If we’ve started off with a route from a pushState-enabled browser, but we’re currently in a browser that doesn’t support it…

    @@ -4272,17 +4309,17 @@ browser, but we’re currently in a browser that doesn’t support it…

            if (!this._hasPushState && !this.atRoot()) {
    -          var root = this.root.slice(0, -1) || '/';
    -          this.location.replace(root + '#' + this.getPath());
    + var rootPath = this.root.slice(0, -1) || '/'; + this.location.replace(rootPath + '#' + this.getPath());
  • -
  • +
  • - +

    Return immediately as browser will do redirect to new url

    @@ -4293,11 +4330,11 @@ browser, but we’re currently in a browser that doesn’t support it…

  • -
  • +
  • - +

    Or if we’ve started out with a hash-based route, but we’re currently in a browser where it could be pushState-based instead…

    @@ -4313,11 +4350,11 @@ in a browser where it could be pushState-based instead…

  • -
  • +
  • - +

    Proxy an iframe to handle location events if the browser doesn’t support the hashchange event, HTML5 history, or the user wants @@ -4326,29 +4363,47 @@ support the hashchange event, HTML5 history, or the user wants

          if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
    -        var iframe = document.createElement('iframe');
    -        iframe.src = 'javascript:0';
    -        iframe.style.display = 'none';
    -        iframe.tabIndex = -1;
    +        this.iframe = document.createElement('iframe');
    +        this.iframe.src = 'javascript:0';
    +        this.iframe.style.display = 'none';
    +        this.iframe.tabIndex = -1;
             var body = document.body;
  • +
  • +
    + +
    + +
    +

    Using appendChild will throw on IE < 9 if the document is not ready.

    + +
    + +
            var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
    +        iWindow.document.open();
    +        iWindow.document.close();
    +        iWindow.location.hash = '#' + this.fragment;
    +      }
    + +
  • + +
  • -

    Using appendChild will throw on IE < 9 if the document is not ready.

    +

    Add a cross-platform addEventListener shim for older browsers.

    -
            this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow;
    -        this.iframe.document.open().close();
    -        this.iframe.location.hash = '#' + this.fragment;
    -      }
    +
          var addEventListener = window.addEventListener || function(eventName, listener) {
    +        return attachEvent('on' + eventName, listener);
    +      };
  • @@ -4359,23 +4414,6 @@ support the hashchange event, HTML5 history, or the user wants
    -

    Add a cross-platform addEventListener shim for older browsers.

    - - - -
          var addEventListener = window.addEventListener || function (eventName, listener) {
    -        return attachEvent('on' + eventName, listener);
    -      };
    - - - - -
  • -
    - -
    - -

    Depending on whether we’re using pushState or hashes, and whether ‘onhashchange’ is supported, determine how we check the URL state.

    @@ -4395,18 +4433,35 @@ support the hashchange event, HTML5 history, or the user wants
  • -
  • +
  • - +

    Disable Backbone.history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers.

    -
        stop: function() {
    +
        stop: function() {
    + +
  • + + +
  • +
    + +
    + +
    +

    Add a cross-platform removeEventListener shim for older browsers.

    + +
    + +
          var removeEventListener = window.removeEventListener || function(eventName, listener) {
    +        return detachEvent('on' + eventName, listener);
    +      };
  • @@ -4417,23 +4472,6 @@ but possibly useful for unit testing Routers.

    -

    Add a cross-platform removeEventListener shim for older browsers.

    - - - -
          var removeEventListener = window.removeEventListener || function (eventName, listener) {
    -        return detachEvent('on' + eventName, listener);
    -      };
    - - - - -
  • -
    - -
    - -

    Remove window listeners.

    @@ -4447,29 +4485,29 @@ but possibly useful for unit testing Routers.

  • -
  • +
  • - +

    Clean up the iframe if necessary.

          if (this.iframe) {
    -        document.body.removeChild(this.iframe.frameElement);
    +        document.body.removeChild(this.iframe);
             this.iframe = null;
           }
  • -
  • +
  • - +

    Some environments will throw when clearing an undefined interval.

    @@ -4482,54 +4520,54 @@ but possibly useful for unit testing Routers.

  • -
  • +
  • - +

    Add a route to be tested when the fragment changes. Routes added later may override previous routes.

    -
        route: function(route, callback) {
    +            
        route: function(route, callback) {
           this.handlers.unshift({route: route, callback: callback});
         },
  • +
  • +
    + +
    + +
    +

    Checks the current URL to see if it has changed, and if it has, +calls loadUrl, normalizing across the hidden iframe.

    + +
    + +
        checkUrl: function(e) {
    +      var current = this.getFragment();
    + +
  • + +
  • -

    Checks the current URL to see if it has changed, and if it has, -calls loadUrl, normalizing across the hidden iframe.

    - -
    - -
        checkUrl: function(e) {
    -      var current = this.getFragment();
    - -
  • - - -
  • -
    - -
    - -

    If the user pressed the back button, the iframe’s hash will have changed and we should use that for comparison.

          if (current === this.fragment && this.iframe) {
    -        current = this.getHash(this.iframe);
    +        current = this.getHash(this.iframe.contentWindow);
           }
     
           if (current === this.fragment) return false;
    @@ -4540,11 +4578,11 @@ changed and we should use that for comparison.

  • -
  • +
  • - +

    Attempt to load the current URL fragment. If a route succeeds with a match, returns true. If no defined routes matches the fragment, @@ -4552,16 +4590,16 @@ returns false.

    -
        loadUrl: function(fragment) {
    +
        loadUrl: function(fragment) {
  • -
  • +
  • - +

    If the root doesn’t match, no routes can match either.

    @@ -4569,7 +4607,7 @@ returns false.

          if (!this.matchRoot()) return false;
           fragment = this.fragment = this.getFragment(fragment);
    -      return _.any(this.handlers, function(handler) {
    +      return _.some(this.handlers, function(handler) {
             if (handler.route.test(fragment)) {
               handler.callback(fragment);
               return true;
    @@ -4580,11 +4618,11 @@ returns false.

  • -
  • +
  • - +

    Save a fragment into the hash history, or replace the URL state if the ‘replace’ option is passed. You are responsible for properly URL-encoding @@ -4595,18 +4633,18 @@ you wish to modify the current URL without adding an entry to the history.

    -
        navigate: function(fragment, options) {
    +            
        navigate: function(fragment, options) {
           if (!History.started) return false;
           if (!options || options === true) options = {trigger: !!options};
  • -
  • +
  • - +

    Normalize the fragment.

    @@ -4617,30 +4655,30 @@ you wish to modify the current URL without adding an entry to the history.

  • -
  • +
  • - +

    Don’t include a trailing slash on the root.

    -
          var root = this.root;
    +            
          var rootPath = this.root;
           if (fragment === '' || fragment.charAt(0) === '?') {
    -        root = root.slice(0, -1) || '/';
    +        rootPath = rootPath.slice(0, -1) || '/';
           }
    -      var url = root + fragment;
    + var url = rootPath + fragment;
  • -
  • +
  • - +

    Strip the hash and decode for matching.

    @@ -4654,11 +4692,11 @@ you wish to modify the current URL without adding an entry to the history.

  • -
  • +
  • - +

    If pushState is available, we use it to set the fragment as a real URL.

    @@ -4670,11 +4708,11 @@ you wish to modify the current URL without adding an entry to the history.

  • -
  • +
  • - +

    If hash changes haven’t been explicitly disabled, update the hash fragment to store history.

    @@ -4683,7 +4721,31 @@ fragment to store history.

          } else if (this._wantsHashChange) {
             this._updateHash(this.location, fragment, options.replace);
    -        if (this.iframe && (fragment !== this.getHash(this.iframe))) {
    + if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) { + var iWindow = this.iframe.contentWindow;
    + +
  • + + +
  • +
    + +
    + +
    +

    Opening and closing the iframe tricks IE7 and earlier to push a +history entry on hash-tag change. When replace is true, we don’t +want this.

    + +
    + +
              if (!options.replace) {
    +            iWindow.document.open();
    +            iWindow.document.close();
    +          }
    +
    +          this._updateHash(iWindow.location, fragment, options.replace);
    +        }
  • @@ -4694,25 +4756,6 @@ fragment to store history.

    -

    Opening and closing the iframe tricks IE7 and earlier to push a -history entry on hash-tag change. When replace is true, we don’t -want this.

    - - - -
              if (!options.replace) this.iframe.document.open().close();
    -          this._updateHash(this.iframe.location, fragment, options.replace);
    -        }
    - - - - -
  • -
    - -
    - -

    If you’ve told us that you explicitly don’t want fallback hashchange- based history, then navigate becomes a page refresh.

    @@ -4727,18 +4770,18 @@ based history, then navigate becomes a page refresh.

  • -
  • +
  • - +

    Update the hash location, either replacing the current entry, or adding a new one to the browser history.

    -
        _updateHash: function(location, fragment, replace) {
    +            
        _updateHash: function(location, fragment, replace) {
           if (replace) {
             var href = location.href.replace(/(javascript:|#).*$/, '');
             location.replace(href + '#' + fragment);
    @@ -4747,11 +4790,11 @@ a new one to the browser history.

  • -
  • +
  • - +

    Some browsers require that hash contains a leading #.

    @@ -4766,11 +4809,11 @@ a new one to the browser history.

  • -
  • +
  • - +

    Create the default Backbone.history.

    @@ -4781,14 +4824,26 @@ a new one to the browser history.

  • +
  • +
    + +
    + +
    +

    Helpers

    + +
    + +
  • + +
  • -

    Helpers

    - +
  • @@ -4800,9 +4855,16 @@ a new one to the browser history.

    - +

    Helper function to correctly set up the prototype chain for subclasses. +Similar to goog.inherits, but uses a hash of prototype properties and +class properties to be extended.

    + +
      var extend = function(protoProps, staticProps) {
    +    var parent = this;
    +    var child;
    + @@ -4812,15 +4874,17 @@ a new one to the browser history.

    -

    Helper function to correctly set up the prototype chain for subclasses. -Similar to goog.inherits, but uses a hash of prototype properties and -class properties to be extended.

    +

    The constructor function for the new subclass is either defined by you +(the “constructor” property in your extend definition), or defaulted +by us to simply call the parent constructor.

    -
      var extend = function(protoProps, staticProps) {
    -    var parent = this;
    -    var child;
    +
        if (protoProps && _.has(protoProps, 'constructor')) {
    +      child = protoProps.constructor;
    +    } else {
    +      child = function(){ return parent.apply(this, arguments); };
    +    }
    @@ -4831,17 +4895,11 @@ class properties to be extended.

    -

    The constructor function for the new subclass is either defined by you -(the “constructor” property in your extend definition), or defaulted -by us to simply call the parent constructor.

    +

    Add static properties to the constructor function, if supplied.

    -
        if (protoProps && _.has(protoProps, 'constructor')) {
    -      child = protoProps.constructor;
    -    } else {
    -      child = function(){ return parent.apply(this, arguments); };
    -    }
    +
        _.extend(child, parent, staticProps);
    @@ -4852,11 +4910,13 @@ by us to simply call the parent constructor.

    -

    Add static properties to the constructor function, if supplied.

    +

    Set the prototype chain to inherit from parent, without calling +parent‘s constructor function and add the prototype properties.

    -
        _.extend(child, parent, staticProps);
    +
        child.prototype = _.create(parent.prototype, protoProps);
    +    child.prototype.constructor = child;
    @@ -4867,40 +4927,6 @@ by us to simply call the parent constructor.

    -

    Set the prototype chain to inherit from parent, without calling -parent constructor function.

    - - - -
        var Surrogate = function(){ this.constructor = child; };
    -    Surrogate.prototype = parent.prototype;
    -    child.prototype = new Surrogate;
    - - - - -
  • -
    - -
    - -
    -

    Add prototype properties (instance properties) to the subclass, -if supplied.

    - -
    - -
        if (protoProps) _.extend(child.prototype, protoProps);
    - -
  • - - -
  • -
    - -
    - -

    Set a convenience property in case the parent’s prototype is needed later.

    @@ -4914,11 +4940,11 @@ later.

  • -
  • +
  • - +

    Set up inheritance for the model, collection, router, view and history.

    @@ -4929,44 +4955,43 @@ later.

  • -
  • +
  • - +

    Throw an error when a URL is needed, and none is supplied.

    -
      var urlError = function() {
    +            
      var urlError = function() {
         throw new Error('A "url" property or function must be specified');
       };
  • -
  • +
  • - +

    Wrap an optional error callback with a fallback error event.

    -
      var wrapError = function(model, options) {
    +            
      var wrapError = function(model, options) {
         var error = options.error;
    -    options.error = function(resp) {
    +    options.error = function(resp) {
           if (error) error.call(options.context, model, resp, options);
           model.trigger('error', model, resp, options);
         };
       };
     
       return Backbone;
    -
    -}));
    +});
  • diff --git a/docs/backbone.localStorage.html b/docs/backbone.localStorage.html index b4bd2bd1..42c42c46 100644 --- a/docs/backbone.localStorage.html +++ b/docs/backbone.localStorage.html @@ -59,7 +59,7 @@ * * https://github.com/jeromegn/Backbone.localStorage */ -(function (root, factory) { +(function (root, factory) { if (typeof define === "function" && define.amd) { @@ -75,7 +75,7 @@ -
          define(["underscore","backbone"], function(_, Backbone) {
    +
          define(["underscore","backbone"], function(_, Backbone) {
    @@ -109,7 +109,7 @@
          factory(_, Backbone);
        }
    -}(this, function(_, Backbone) {
    +}(this, function(_, Backbone) { @@ -153,7 +153,7 @@ to make things work even if they are removed from the global namespace

    -
    function S4() {
    +            
    function S4() {
        return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
     };
    @@ -170,7 +170,7 @@ to make things work even if they are removed from the global namespace

    -
    function guid() {
    +            
    function guid() {
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
     };
    @@ -185,11 +185,11 @@ to make things work even if they are removed from the global namespace

    Our Store is represented by a single JS object in localStorage. Create it with a meaningful name, like the name you’d give a table. -window.Store is deprectated, use Backbone.LocalStorage instead

    +window.Store is deprecated, use Backbone.LocalStorage instead

    -
    Backbone.LocalStorage = window.Store = function(name) {
    +            
    Backbone.LocalStorage = window.Store = function(name) {
       this.name = name;
       var store = this.localStorage().getItem(this.name);
       this.records = (store && store.split(",")) || [];
    @@ -210,7 +210,7 @@ _.extend(Backbone.LocalStorage.prototype, {
    -
      save: function() {
    +            
      save: function() {
         this.localStorage().setItem(this.name, this.records.join(","));
       },
    @@ -228,7 +228,7 @@ have an id of it’s own.

    -
      create: function(model) {
    +            
      create: function(model) {
         if (!model.id) {
           model.id = guid();
           model.set(model.idAttribute, model.id);
    @@ -252,7 +252,7 @@ have an id of it’s own.

    -
      update: function(model) {
    +            
      update: function(model) {
         this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
         if (!_.include(this.records, model.id.toString()))
           this.records.push(model.id.toString()); this.save();
    @@ -272,7 +272,7 @@ have an id of it’s own.

    -
      find: function(model) {
    +            
      find: function(model) {
         return this.jsonData(this.localStorage().getItem(this.name+"-"+model.id));
       },
    @@ -289,9 +289,9 @@ have an id of it’s own.

    -
      findAll: function() {
    +            
      findAll: function() {
         return _(this.records).chain()
    -      .map(function(id){
    +      .map(function(id){
             return this.jsonData(this.localStorage().getItem(this.name+"-"+id));
           }, this)
           .compact()
    @@ -311,18 +311,18 @@ have an id of it’s own.

    -
      destroy: function(model) {
    +            
      destroy: function(model) {
         if (model.isNew())
           return false
         this.localStorage().removeItem(this.name+"-"+model.id);
    -    this.records = _.reject(this.records, function(id){
    +    this.records = _.reject(this.records, function(id){
           return id === model.id.toString();
         });
         this.save();
         return model;
       },
     
    -  localStorage: function() {
    +  localStorage: function() {
         return localStorage;
       },
    @@ -339,7 +339,7 @@ have an id of it’s own.

    -
      jsonData: function (data) {
    +            
      jsonData: function (data) {
           return data && JSON.parse(data);
       }
     
    @@ -360,7 +360,7 @@ window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStora
     
                 
    -
    Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
    +            
    Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
       var store = model.localStorage || model.collection.localStorage;
     
       var resp, errorMessage, syncDfd = $.Deferred && $.Deferred(); //If $ is having Deferred - use it.
    @@ -427,7 +427,7 @@ always execute callback for success and error

    Backbone.ajaxSync = Backbone.sync; -Backbone.getSyncMethod = function(model) { +Backbone.getSyncMethod = function(model) { if(model.localStorage || (model.collection && model.collection.localStorage)) { return Backbone.localSync; } @@ -449,7 +449,7 @@ the original ‘Backbone.sync’ is still available in ‘Backbone.ajaxSync’ -
    Backbone.sync = function(method, model, options) {
    +            
    Backbone.sync = function(method, model, options) {
       return Backbone.getSyncMethod(model).apply(this, [method, model, options]);
     };
     
    diff --git a/docs/jsl.conf b/docs/jsl.conf
    deleted file mode 100644
    index cc525662..00000000
    --- a/docs/jsl.conf
    +++ /dev/null
    @@ -1,44 +0,0 @@
    -# JavaScriptLint configuration file for Backbone.
    -
    -+no_return_value              # function {0} does not always return a value
    -+duplicate_formal             # duplicate formal argument {0}
    --equal_as_assign              # test for equality (==) mistyped as assignment (=)?{0}
    -+var_hides_arg                # variable {0} hides argument
    -+redeclared_var               # redeclaration of {0} {1}
    --anon_no_return_value         # anonymous function does not always return a value
    -+missing_semicolon            # missing semicolon
    -+meaningless_block            # meaningless block; curly braces have no impact
    --comma_separated_stmts        # multiple statements separated by commas (use semicolons?)
    -+unreachable_code             # unreachable code
    -+missing_break                # missing break statement
    -+missing_break_for_last_case  # missing break statement for last case in switch
    --comparison_type_conv         # comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==)
    --inc_dec_within_stmt          # increment (++) and decrement (--) operators used as part of greater statement
    --useless_void                 # use of the void type may be unnecessary (void is always undefined)
    -+multiple_plus_minus          # unknown order of operations for successive plus (e.g. x+++y) or minus (e.g. x---y) signs
    -+use_of_label                 # use of label
    --block_without_braces         # block statement without curly braces
    -+leading_decimal_point        # leading decimal point may indicate a number or an object member
    -+trailing_decimal_point       # trailing decimal point may indicate a number or an object member
    -+octal_number                 # leading zeros make an octal number
    -+nested_comment               # nested comment
    -+misplaced_regex              # regular expressions should be preceded by a left parenthesis, assignment, colon, or comma
    --ambiguous_newline            # unexpected end of line; it is ambiguous whether these lines are part of the same statement
    -+empty_statement              # empty statement or extra semicolon
    --missing_option_explicit      # the "option explicit" control comment is missing
    -+partial_option_explicit      # the "option explicit" control comment, if used, must be in the first script tag
    -+dup_option_explicit          # duplicate "option explicit" control comment
    -+useless_assign               # useless assignment
    -+ambiguous_nested_stmt        # block statements containing block statements should use curly braces to resolve ambiguity
    -+ambiguous_else_stmt          # the else statement could be matched with one of multiple if statements (use curly braces to indicate intent)
    --missing_default_case         # missing default case in switch statement
    -+duplicate_case_in_switch     # duplicate case in switch statements
    -+default_not_at_end           # the default case is not at the end of the switch statement
    -+legacy_cc_not_understood     # couldn't understand control comment using /*@keyword@*/ syntax
    -+jsl_cc_not_understood        # couldn't understand control comment using /*jsl:keyword*/ syntax
    -+useless_comparison           # useless comparison; comparing identical expressions
    -+with_statement               # with statement hides undeclared variables; use temporary variable instead
    -+trailing_comma_in_array      # extra comma is not recommended in array initializers
    -+assign_to_function_call      # assignment to a function call
    -+parseint_missing_radix       # parseInt missing radix parameter
    -+lambda_assign_requires_semicolon
    diff --git a/docs/search.js b/docs/search.js
    new file mode 100644
    index 00000000..97ae6213
    --- /dev/null
    +++ b/docs/search.js
    @@ -0,0 +1,58 @@
    +(function() {
    +  var functions = document.querySelectorAll('[data-name]');
    +  var sections = document.querySelectorAll('.searchable_section');
    +  var searchInput = document.getElementById('function_filter');
    +
    +  function strIn(a, b) {
    +    a = a.toLowerCase();
    +    b = b.toLowerCase();
    +    return b.indexOf(a) >= 0;
    +  }
    +
    +  function doesMatch(element) {
    +    var name = element.getAttribute('data-name');
    +    var aliases = element.getAttribute('data-aliases') || '';
    +    return strIn(searchInput.value, name) || strIn(searchInput.value, aliases);
    +  }
    +
    +  function filterElement(element) {
    +    element.style.display = doesMatch(element) ? '' : 'none';
    +  }
    +
    +  function filterToc() {
    +    _.each(functions, filterElement);
    +
    +    var emptySearch = searchInput.value === '';
    +
    +    // Hide the titles of empty sections
    +    _.each(sections, function(section) {
    +      var sectionFunctions = section.querySelectorAll('[data-name]');
    +      var showSection = emptySearch || _.some(sectionFunctions, doesMatch);
    +      section.style.display = showSection ? '' : 'none';
    +    });
    +  }
    +
    +  function gotoFirst() {
    +    var firstFunction = _.find(functions, doesMatch);
    +    if(firstFunction) {
    +      window.location.hash = firstFunction.lastChild.getAttribute('href');
    +      searchInput.focus();
    +    }
    +  }
    +
    +  searchInput.addEventListener('input', filterToc, false);
    +
    +  // Press "Enter" to jump to the first matching function
    +  searchInput.addEventListener('keypress', function(e) {
    +    if (e.which === 13) {
    +      gotoFirst();
    +    }
    +  });
    +
    +  // Press "/" to search
    +  document.body.addEventListener('keyup', function(event) {
    +    if (191 === event.which) {
    +      searchInput.focus();
    +    }
    +  });
    +}());
    diff --git a/docs/todos.html b/docs/todos.html
    index 559ec230..1ac4e52b 100644
    --- a/docs/todos.html
    +++ b/docs/todos.html
    @@ -52,7 +52,7 @@
                   

    An example Backbone application contributed by Jérôme Gravel-Niquet. This demo uses a simple -LocalStorage adapter +LocalStorage adapter to persist Backbone models within your browser.

    @@ -70,7 +70,7 @@ to persist Backbone models within your browser.

    -
    $(function(){
    +
    $(function(){
    @@ -125,7 +125,7 @@ to persist Backbone models within your browser.

    -
        defaults: function() {
    +            
        defaults: function() {
           return {
             title: "empty todo...",
             order: Todos.nextOrder(),
    @@ -146,7 +146,7 @@ to persist Backbone models within your browser.

    -
        toggle: function() {
    +            
        toggle: function() {
           this.save({done: !this.get("done")});
         }
     
    @@ -236,7 +236,7 @@ server.

    -
        done: function() {
    +            
        done: function() {
           return this.where({done: true});
         },
    @@ -253,7 +253,7 @@ server.

    -
        remaining: function() {
    +            
        remaining: function() {
           return this.where({done: false});
         },
    @@ -271,7 +271,7 @@ GUID in the database. This generates the next order number for new items.

    -
        nextOrder: function() {
    +            
        nextOrder: function() {
           if (!this.length) return 1;
           return this.last().get('order') + 1;
         },
    @@ -414,7 +414,7 @@ app, we set a direct reference on the model for convenience.

    -
        initialize: function() {
    +            
        initialize: function() {
           this.listenTo(this.model, 'change', this.render);
           this.listenTo(this.model, 'destroy', this.remove);
         },
    @@ -432,7 +432,7 @@ app, we set a direct reference on the model for convenience.

    -
        render: function() {
    +            
        render: function() {
           this.$el.html(this.template(this.model.toJSON()));
           this.$el.toggleClass('done', this.model.get('done'));
           this.input = this.$('.edit');
    @@ -452,7 +452,7 @@ app, we set a direct reference on the model for convenience.

    -
        toggleDone: function() {
    +            
        toggleDone: function() {
           this.model.toggle();
         },
    @@ -469,7 +469,7 @@ app, we set a direct reference on the model for convenience.

    -
        edit: function() {
    +            
        edit: function() {
           this.$el.addClass("editing");
           this.input.focus();
         },
    @@ -487,7 +487,7 @@ app, we set a direct reference on the model for convenience.

    -
        close: function() {
    +            
        close: function() {
           var value = this.input.val();
           if (!value) {
             this.clear();
    @@ -510,7 +510,7 @@ app, we set a direct reference on the model for convenience.

    -
        updateOnEnter: function(e) {
    +            
        updateOnEnter: function(e) {
           if (e.keyCode == 13) this.close();
         },
    @@ -527,7 +527,7 @@ app, we set a direct reference on the model for convenience.

    -
        clear: function() {
    +            
        clear: function() {
           this.model.destroy();
         }
     
    @@ -638,7 +638,7 @@ loading any preexisting todos that might be saved in localStorage.

    -
        initialize: function() {
    +            
        initialize: function() {
     
           this.input = this.$("#new-todo");
           this.allCheckbox = this.$("#toggle-all")[0];
    @@ -662,12 +662,12 @@ loading any preexisting todos that might be saved in localStorage.

    -

    Re-rendering the App just means refreshing the statistics — the rest +

    Re-rendering the App just means refreshing the statistics – the rest of the app doesn’t change.

    -
        render: function() {
    +            
        render: function() {
           var done = Todos.done().length;
           var remaining = Todos.remaining().length;
     
    @@ -697,7 +697,7 @@ appending its element to the <ul>.

    -
        addOne: function(todo) {
    +            
        addOne: function(todo) {
           var view = new TodoView({model: todo});
           this.$("#todo-list").append(view.render().el);
         },
    @@ -715,7 +715,7 @@ appending its element to the <ul>.

    -
        addAll: function() {
    +            
        addAll: function() {
           Todos.each(this.addOne, this);
         },
    @@ -733,7 +733,7 @@ persisting it to localStorage.

    -
        createOnEnter: function(e) {
    +            
        createOnEnter: function(e) {
           if (e.keyCode != 13) return;
           if (!this.input.val()) return;
     
    @@ -754,14 +754,14 @@ persisting it to localStorage.

    -
        clearCompleted: function() {
    +            
        clearCompleted: function() {
           _.invoke(Todos.done(), 'destroy');
           return false;
         },
     
    -    toggleAllComplete: function () {
    +    toggleAllComplete: function () {
           var done = this.allCheckbox.checked;
    -      Todos.each(function (todo) { todo.save({'done': done}); });
    +      Todos.each(function (todo) { todo.save({'done': done}); });
         }
     
       });
    diff --git a/examples/backbone.localStorage.js b/examples/backbone.localStorage.js index 0aab2478..4ca7fe0e 100644 --- a/examples/backbone.localStorage.js +++ b/examples/backbone.localStorage.js @@ -35,7 +35,7 @@ function guid() { // Our Store is represented by a single JS object in *localStorage*. Create it // with a meaningful name, like the name you'd give a table. -// window.Store is deprectated, use Backbone.LocalStorage instead +// window.Store is deprecated, use Backbone.LocalStorage instead Backbone.LocalStorage = window.Store = function(name) { this.name = name; var store = this.localStorage().getItem(this.name); diff --git a/examples/todos/index.html b/examples/todos/index.html index 6f778783..e737fd2c 100644 --- a/examples/todos/index.html +++ b/examples/todos/index.html @@ -37,7 +37,7 @@ Created by
    Jérôme Gravel-Niquet. -
    Rewritten by: TodoMVC. +
    Rewritten by: TodoMVC.
    diff --git a/examples/todos/todos.js b/examples/todos/todos.js index a0bb16ef..91e55c31 100644 --- a/examples/todos/todos.js +++ b/examples/todos/todos.js @@ -1,6 +1,6 @@ // An example Backbone application contributed by // [Jérôme Gravel-Niquet](http://jgn.me/). This demo uses a simple -// [LocalStorage adapter](backbone.localstorage.html) +// [LocalStorage adapter](backbone.localStorage.html) // to persist Backbone models within your browser. // Load the application once the DOM is ready, using `jQuery.ready`: diff --git a/index.html b/index.html index 83955ea9..83036d26 100644 --- a/index.html +++ b/index.html @@ -48,7 +48,7 @@ margin: 5px 0 0 0; padding-left: 0px; list-style-type: none; - font-family: Lucida Grande; + font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif; } .toc_section li { cursor: pointer; @@ -61,6 +61,9 @@ .toc_section li a:hover { text-decoration: underline; } + input#function_filter { + width: 80%; + } div.container { position: relative; width: 550px; @@ -300,233 +303,261 @@ @@ -577,13 +608,13 @@ - - + + - + @@ -600,14 +631,14 @@

    Backbone's only hard dependency is - Underscore.js ( >= 1.7.0). + Underscore.js ( >= 1.8.3). For RESTful persistence and DOM manipulation with Backbone.View, - include jQuery ( >= 1.11.0), and + include jQuery ( >= 1.11.0), and json2.js for older Internet Explorer support. (Mimics of the Underscore and jQuery APIs, such as - Lo-Dash and - Zepto, will + Lodash and + Zepto, will also tend to work, with varying degrees of compatibility.)

    Getting Started

    @@ -673,7 +704,7 @@ Model
    • Orchestrates data and business logic.
    • -
    • Loads and saves from the server.
    • +
    • Loads and saves data from the server.
    • Emits events when data changes.
    @@ -868,11 +899,6 @@ object.trigger("alert", "an event"); book.on("change:title change:author", ...); -

    - To supply a context value for this when the callback is invoked, - pass the optional third argument: model.on('change', this.render, this) -

    -

    Callbacks bound to the special "all" event will be triggered when any event occurs, and are passed @@ -893,12 +919,18 @@ proxy.on("all", function(eventName) {

     book.on({
    -  "change:title": titleView.update,
       "change:author": authorPane.update,
    +  "change:title change:subtitle": titleView.update,
       "destroy": bookView.remove
     });
     
    +

    + To supply a context value for this when the callback is invoked, + pass the optional last argument: model.on('change', this.render, this) or + model.on({change: this.render}, this). +

    +

    offobject.off([event], [callback], [context])Alias: unbind
    @@ -999,20 +1031,20 @@ view.stopListening(model);

    • "add" (model, collection, options) — when a model is added to a collection.
    • "remove" (model, collection, options) — when a model is removed from a collection.
    • -
    • "update" (collection, options) — single event triggered after any number of models have been added or removed from a collection.
    • -
    • "reset" (collection, options) — when the collection's entire contents have been replaced.
    • +
    • "update" (collection, options) — single event triggered after any number of models have been added, removed or changed in a collection.
    • +
    • "reset" (collection, options) — when the collection's entire contents have been reset.
    • "sort" (collection, options) — when the collection has been re-sorted.
    • "change" (model, options) — when a model's attributes have changed.
    • "change:[attribute]" (model, value, options) — when a specific attribute has been updated.
    • "destroy" (model, collection, options) — when a model is destroyed.
    • "request" (model_or_collection, xhr, options) — when a model or collection has started a request to the server.
    • -
    • "sync" (model_or_collection, resp, options) — when a model or collection has been successfully synced with the server.
    • -
    • "error" (model_or_collection, resp, options) — when a model's or collection's request to the server has failed.
    • +
    • "sync" (model_or_collection, response, options) — when a model or collection has been successfully synced with the server.
    • +
    • "error" (model_or_collection, response, options) — when a model's or collection's request to the server has failed.
    • "invalid" (model, error, options) — when a model's validation fails on the client.
    • "route:[name]" (params) — Fired by the router when a specific route is matched.
    • "route" (route, params) — Fired by the router when any route has been matched.
    • "route" (router, route, params) — Fired by history when any route has been matched.
    • -
    • "all" — this special event fires for any triggered event, passing the event name as the first argument.
    • +
    • "all" — this special event fires for any triggered event, passing the event name as the first argument followed by all trigger arguments.

    @@ -1240,6 +1272,8 @@ if (note.has("title")) { A special property of models, the id is an arbitrary string (integer id or UUID). If you set the id in the attributes hash, it will be copied onto the model as a direct property. + model.id should not be manipulated directly, + it should be modified only via model.set('id', …). Models can be retrieved by id from collections, and the id is used to generate model URLs by default.

    @@ -1484,7 +1518,6 @@ book.destroy({success: function(model, response) {
  • invert
  • pick
  • omit
  • -
  • matches
  • chain
  • isEmpty
  • @@ -1738,7 +1771,7 @@ bill.set({name : "Bill Jones"});

    - modelcollection.model + modelcollection.model([attrs], [options])
    Override this property to specify the model class that the collection contains. If defined, you can pass raw attributes objects (and arrays) to @@ -1770,6 +1803,41 @@ var Library = Backbone.Collection.extend({ } }); + + +

    + modelIdcollection.modelId(attrs) +
    + Override this method to return the value the collection will use to + identify a model given its attributes. Useful for combining models from + multiple tables with different idAttribute + values into a single collection. +

    + +

    + By default returns the value of the attributes' + idAttribute + from the collection's model class or failing that, id. If + your collection uses a model factory and + those models have an idAttribute other than id you must + override this method. +

    + +
    +var Library = Backbone.Collection.extend({
    +  modelId: function(attrs) {
    +    return attrs.type + attrs.id;
    +  }
    +});
    +
    +var library = new Library([
    +  {type: 'dvd', id: 1},
    +  {type: 'vhs', id: 1}
    +]);
    +
    +var dvdId = library.get('dvd1').id;
    +var vhsId = library.get('vhs1').id;
    +alert('dvd: ' + dvdId + ', vhs: ' + vhsId);
     

    @@ -1787,7 +1855,7 @@ var Library = Backbone.Collection.extend({

     var tabs = new TabSet([tab1, tab2, tab3]);
    -var spaces = new Backbone.Collection([], {
    +var spaces = new Backbone.Collection(null, {
       model: Space
     });
     
    @@ -1837,17 +1905,24 @@ alert(JSON.stringify(collection)); you can take a look at the Underscore documentation for the full details…

    +

    + Most methods can take an object or string to support model-attribute-style + predicates or a function that receives the model instance as an argument. +

    +
    • forEach (each)
    • map (collect)
    • reduce (foldl, inject)
    • reduceRight (foldr)
    • find (detect)
    • +
    • findIndex
    • +
    • findLastIndex
    • filter (select)
    • reject
    • every (all)
    • some (any)
    • -
    • contains (include)
    • +
    • contains (includes)
    • invoke
    • max
    • min
    • @@ -1877,17 +1952,15 @@ books.each(function(book) { book.publish(); }); -var titles = books.map(function(book) { - return book.get("title"); -}); +var titles = books.map("title"); -var publishedBooks = books.filter(function(book) { - return book.get("published") === true; -}); +var publishedBooks = books.filter({published: true}); var alphabetical = books.sortBy(function(book) { return book.author.get("name").toLowerCase(); }); + +var randomThree = books.sample(3);

      @@ -1930,7 +2003,7 @@ ships.add([ object, any value acceptable as the id argument of collection.get. Fires a "remove" event for each model, and a single - "update" event afterwards. + "update" event afterwards, unless {silent: true} is passed. The model's index before removal is available to listeners as options.index.

      @@ -1942,7 +2015,8 @@ ships.add([ you have so many models to change that you'd rather just update the collection in bulk. Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event - at the end. Returns the newly-set models. + on completion, and without triggering any add or remove events on any models. + Returns the newly-set models. For convenience, within a "reset" event, the list of any previous models is available as options.previousModels.
      Pass null for models to empty your Collection with options. @@ -2005,7 +2079,8 @@ var book = library.get(110);
      Get a model from a collection, specified by index. Useful if your collection is sorted, and if your collection isn't sorted, at will still - retrieve models in insertion order. + retrieve models in insertion order. When passed a negative index, it + will retrieve the model from the back of the collection.

      @@ -2041,7 +2116,7 @@ var book = library.get(110);
      Return a shallow copy of this collection's models, using the same options as native - Array#slice. + Array#slice.

      @@ -2062,7 +2137,7 @@ var book = library.get(110); sortBy (pass a function that takes a single argument), as a - sort + sort (pass a comparator function that expects two arguments), or as a string indicating the attribute to sort by.

      @@ -2156,6 +2231,7 @@ alert(musketeers.length);
      Just like where, but directly returns only the first model in the collection that matches the passed attributes. + If no model matches returns undefined.

      @@ -2362,8 +2438,8 @@ var Workspace = Backbone.Router.extend({

      A route of "file/*path" will match - #file/nested/folder/file.txt, passing - "nested/folder/file.txt" to the action. + #file/folder/file.txt, passing + "folder/file.txt" to the action.

      @@ -2373,6 +2449,13 @@ var Workspace = Backbone.Router.extend({ and "installing" to the action in the second.

      +

      + A nested optional route of "docs(/:section)(/:subsection)" will match + #docs, #docs/faq, and #docs/faq/installing, + passing "faq" to the action in the second case, and passing "faq" + and "installing" to the action in the third. +

      +

      Trailing slashes are treated as part of the URL, and (correctly) treated as a unique route when accessed. docs and docs/ will fire @@ -2625,7 +2708,8 @@ $(function(){

       def update
         account = Account.find params[:id]
      -  account.update_attributes params.require(:account).permit(:name, :otherparam)
      +  permitted = params.require(:account).permit(:name, :otherparam)
      +  account.update_attributes permitted
         render :json => account
       end
       
      @@ -2893,11 +2977,44 @@ var Bookmark = Backbone.View.extend({

      removeview.remove()
      - Removes a view from the DOM, and calls + Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

      +

      + eventsview.events or view.events() +
      + The events hash (or method) can be used to specify a set of DOM + events that will be bound to methods on your View + through delegateEvents. +

      + +

      + Backbone will automatically attach the event listeners at instantiation + time, right before invoking initialize. +

      + +
      +var ENTER_KEY = 13;
      +var InputView = Backbone.View.extend({
      +
      +  tagName: 'input',
      +
      +  events: {
      +    "keydown" : "keyAction",
      +  },
      +
      +  render: function() { ... },
      +
      +  keyAction: function(e) {
      +    if (e.which === ENTER_KEY) {
      +      this.collection.add({text: this.$el.val()});
      +    }
      +  }
      +});
      +
      +

      delegateEventsdelegateEvents([events])
      @@ -2930,6 +3047,12 @@ var Bookmark = Backbone.View.extend({ views which need to behave differently when in different modes.

      +

      + A single-event version of delegateEvents is available as delegate. + In fact, delegateEvents is simply a multi-event wrapper around delegate. + A counterpart to undelegateEvents is available as undelegate. +

      +

      A view that displays a document in a search result might look something like this: @@ -3216,7 +3339,7 @@ inbox.messages.fetch({reset: true});

      You have to escape - </ within the JSON string, to prevent javascript injection + </ within the JSON string, to prevent JavaScript injection attacks.

      @@ -3475,7 +3598,7 @@ ActiveRecord::Base.include_root_in_json = false Earth.nullschool.net displays real-time weather conditions on an interactive animated globe, and Backbone provides the foundation upon which all of the site's components are built. Despite the - presence of several other javascript libraries, Backbone's non-opinionated + presence of several other JavaScript libraries, Backbone's non-opinionated design made it effortless to mix-in the Events functionality used for distributing state changes throughout the page. When the decision was made to switch to Backbone, large blocks of custom logic simply disappeared. @@ -3798,7 +3921,7 @@ ActiveRecord::Base.include_root_in_json = false large single-page application that benefits from Backbone's structure and modularity. ZocDoc's Backbone classes are tested with - Jasmine, and delivered + Jasmine, and delivered to the end user with Cassette.

      @@ -3936,7 +4059,7 @@ ActiveRecord::Base.include_root_in_json = false SoundCloud Mobile. The project uses the public SoundCloud API as a data source (channeled through a nginx proxy), - jQuery templates + jQuery templates for the rendering, Qunit and PhantomJS for the testing suite. The JS code, templates and CSS are built for the @@ -4206,6 +4329,114 @@ ActiveRecord::Base.include_root_in_json = false

      Change Log

      + 1.3.3Apr. 5, 2016 + — Diff + — Docs +
      +
        +
      • + Added findIndex and findLastIndex Underscore methods to + Collection. +
      • +
      • + Added options.changes to Collection "update" event which + includes added, merged, and removed models. +
      • +
      • + Ensured Collection#reduce and Collection#reduceRight + work without an initial accumulator value. +
      • +
      • + Ensured Collection#_removeModels always returns an array. +
      • +
      • + Fixed a bug where Events.once with object syntax failed to bind + context. +
      • +
      • + Fixed Collection#_onModelEvent regression where triggering a + change event without a model would error. +
      • +
      • + Fixed Collection#set regression when parse returns a + falsy value. +
      • +
      • + Fixed Model#id regression where id would be + unintentionally undefined. +
      • +
      • + Fixed _removeModels regression which could cause an infinite loop + under certain conditions. +
      • +
      • + Removed component package support. +
      • +
      • + Note that 1.3.3 fixes several bugs in versions 1.3.0 to 1.3.2. Please upgrade + immediately if you are on one of those versions. +
      • +
      + + 1.2.3Sept. 3, 2015 + — Diff + — Docs +
      +
        +
      • + Fixed a minor regression in 1.2.2 that would cause an error when adding + a model to a collection at an out of bounds index. +
      • +
      + + 1.2.2Aug. 19, 2015 + — Diff + — Docs +
      +
        +
      • + Collection methods find, filter, reject, every, + some, and partition can now take a model-attributes-style predicate: + this.collection.reject({user: 'guybrush'}). +
      • +
      • + Backbone Events once again supports multiple-event maps + (obj.on({'error change': action})). This was a previously + undocumented feature inadvertently removed in 1.2.0. +
      • +
      • + Added Collection#includes as an alias of Collection#contains + and as a replacement for Collection#include in Underscore.js >= 1.8. +
      • +
      + + 1.2.1Jun. 4, 2015 + — Diff + — Docs +
      +
        +
      • + Collection#add now avoids trying to parse a model instance when passed parse: false. +
      • +
      • + Bug fix in Collection#remove. The removed models are now actually returned. +
      • +
      • + Model#fetch no longer parses the response when passing parse: false. +
      • +
      • + Bug fix for iframe-based History when used with JSDOM. +
      • +
      • + Bug fix where Collection#invoke was not taking additional arguments. +
      • +
      • + When using on with an event map, you can now pass the context as the + second argument. This was a previously undocumented feature inadvertently + removed in 1.2.0. +
      • +
      + 1.2.0May 13, 2015DiffDocs @@ -4225,11 +4456,19 @@ ActiveRecord::Base.include_root_in_json = false Also on the subject of jQuery, if you're using Backbone with CommonJS (node, browserify, webpack) Backbone will automatically try to load jQuery for you. +
    • + Views now always delegate their events in setElement. + You can no longer modify the events hash or your view's el property in + initialize. +
    • Added an "update" event that triggers after any amount of models are added or removed from a collection. Handy to re-render lists of things without debouncing.
    • +
    • + Collection#at can take a negative index. +
    • Added modelId to Collection for generating unique ids on polymorphic collections. Handy for cases when your model ids would @@ -4540,7 +4779,7 @@ ActiveRecord::Base.include_root_in_json = false
    • To improve the performance of add, options.index - will no longer be set in the `add` event callback. + will no longer be set in the add event callback. collection.indexOf(model) can be used to retrieve the index of a model as necessary.
    • @@ -4654,7 +4893,7 @@ ActiveRecord::Base.include_root_in_json = false A Backbone collection's comparator function may now behave either like a sortBy (pass a function that takes a single argument), - or like a sort + or like a sort (pass a comparator function that expects two arguments). The comparator function is also now bound by default to the collection — so you can refer to this within it. @@ -4859,6 +5098,7 @@ ActiveRecord::Base.include_root_in_json = false +
    Development Version (1.2.0)69kb, Full source, tons of commentsDevelopment Version (1.3.3)72kb, Full source, tons of comments
    Production Version (1.2.0)Production Version (1.3.3) - 7.3kb, Packed and gzipped
    + 7.6kb, Packed and gzipped
    (Source Map)