├── .gitignore ├── .travis.yml ├── bower.json ├── .jshintrc ├── package.json ├── LICENSE ├── spec ├── support │ └── matchers.js ├── lib │ ├── underscore.js │ └── backbone.js └── backbone.fetch-cache.spec.js ├── Gruntfile.js ├── backbone.fetch-cache.min.js ├── readme.md └── backbone.fetch-cache.js /.gitignore: -------------------------------------------------------------------------------- 1 | .grunt 2 | .DS_Store 3 | node_modules/* 4 | _SpecRunner.html -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 0.10 4 | before_script: 5 | - npm install -g grunt-cli 6 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "backbone-fetch-cache", 3 | "version": "2.0.1", 4 | "homepage": "https://github.com/madglory/backbone-fetch-cache", 5 | "authors": [ 6 | "MadGlory (http://madglory.com)", 7 | "Andrew Appleton " 8 | ], 9 | "description": "Caching for Backbone's fetch method", 10 | "main": "backbone.fetch-cache.js", 11 | "keywords": [ 12 | "backbone", 13 | "fetch", 14 | "cache" 15 | ], 16 | "license": "MIT", 17 | "dependencies": { 18 | "backbone": ">=1.0.0" 19 | }, 20 | "ignore": [ 21 | "node_modules" 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "curly": true, 3 | "eqeqeq": true, 4 | "immed": true, 5 | "latedef": true, 6 | "newcap": true, 7 | "noarg": true, 8 | "sub": true, 9 | "undef": true, 10 | "boss": true, 11 | "eqnull": true, 12 | "browser": true, 13 | "indent": 2, 14 | "globals": { 15 | "$": true, 16 | "_": true, 17 | "Backbone": true, 18 | "define": true, 19 | "it": true, 20 | "describe": true, 21 | "beforeEach": true, 22 | "afterEach": true, 23 | "expect": true, 24 | "spyOn": true, 25 | "jasmine": true, 26 | "sinon": true, 27 | "waitsFor": true, 28 | "runs": true, 29 | "require": true, 30 | "module" : true 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "backbone-fetch-cache", 3 | "version": "2.0.2", 4 | "author": "MadGlory (http://madglory.com)", 5 | "contributors": [ 6 | "Andrew Appleton " 7 | ], 8 | "description": "Caches calls to Backbone.[Model | Collection].fetch", 9 | "license": "MIT", 10 | "scripts": { 11 | "test": "grunt" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/madglory/backbone-fetch-cache.git" 16 | }, 17 | "keywords": [ 18 | "backbone", 19 | "fetch", 20 | "cache" 21 | ], 22 | "main": "./backbone.fetch-cache.js", 23 | "dependencies": {}, 24 | "devDependencies": { 25 | "grunt": "latest", 26 | "grunt-contrib-connect": "", 27 | "grunt-contrib-jasmine": "~0.4.2", 28 | "grunt-contrib-jshint": "~0.4.3", 29 | "grunt-contrib-uglify": "~0.2.0", 30 | "grunt-contrib-watch": "~0.3.1" 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2012-2013 Andrew Appleton, http://floatleft.com 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /spec/support/matchers.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | function isFunc (object) { 3 | return typeof object === 'function'; 4 | } 5 | 6 | beforeEach(function() { 7 | this.addMatchers({ 8 | toBeAPromise: function(expected) { 9 | return ( 10 | isFunc(this.actual.state) && 11 | isFunc(this.actual.always) && 12 | isFunc(this.actual.then) && 13 | isFunc(this.actual.promise) && 14 | isFunc(this.actual.pipe) && 15 | isFunc(this.actual.done) && 16 | isFunc(this.actual.fail) && 17 | isFunc(this.actual.progress) && 18 | !this.actual.hasOwnProperty('notify') && 19 | !this.actual.hasOwnProperty('notifyWith') && 20 | !this.actual.hasOwnProperty('reject') && 21 | !this.actual.hasOwnProperty('rejectWith') && 22 | !this.actual.hasOwnProperty('resolve') && 23 | !this.actual.hasOwnProperty('resolveWith') 24 | ); 25 | }, 26 | toBeResolved: function(expected) { 27 | return this.actual.state() === 'resolved'; 28 | }, 29 | toBeUnresolved: function(expected) { 30 | return this.actual.state() === 'pending'; 31 | } 32 | }); 33 | }); 34 | })(); 35 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | /*global module:false*/ 2 | module.exports = function(grunt) { 3 | 4 | // Project configuration. 5 | grunt.initConfig({ 6 | pkg: grunt.file.readJSON('package.json'), 7 | 8 | jasmine: { 9 | src: ['backbone.fetch-cache.js'], 10 | options: { 11 | helpers: [ 12 | 'spec/support/*.js' 13 | ], 14 | specs : 'spec/**/*.spec.js', 15 | vendor: [ 16 | 'spec/lib/jquery*.js', 17 | 'spec/lib/underscore.js', 18 | 'spec/lib/backbone.js' 19 | ], 20 | timeout : 5000, 21 | phantomjs : { 'ignore-ssl-errors' : true } 22 | } 23 | }, 24 | 25 | connect: { 26 | spec : { 27 | options: { 28 | port : 8000 29 | } 30 | } 31 | }, 32 | 33 | uglify: { 34 | options: { 35 | banner: '/* <%= pkg.name %> v<%= pkg.version %> ' + 36 | "(<%= grunt.template.today('yyyy-mm-dd') %>)\n" + 37 | " by <%= pkg.author %> - <%= pkg.repository.url %>\n" + 38 | ' */\n', 39 | mangle: { 40 | except: ['_', 'Backbone'] 41 | } 42 | }, 43 | dist: { 44 | files: { 45 | 'backbone.fetch-cache.min.js': ['backbone.fetch-cache.js'] 46 | } 47 | } 48 | }, 49 | 50 | watch: { 51 | files: '<%= jshint.files %>', 52 | tasks: ['jshint', 'jasmine'] 53 | }, 54 | 55 | jshint: { 56 | files: ['grunt.js', 'backbone.fetch-cache.js', 'spec/**/*.spec.js'], 57 | options: { 58 | jshintrc: '.jshintrc' 59 | } 60 | } 61 | }); 62 | 63 | grunt.loadNpmTasks('grunt-contrib-jasmine'); 64 | grunt.loadNpmTasks('grunt-contrib-jshint'); 65 | grunt.loadNpmTasks('grunt-contrib-uglify'); 66 | grunt.loadNpmTasks('grunt-contrib-watch'); 67 | grunt.loadNpmTasks('grunt-contrib-connect'); 68 | 69 | grunt.registerTask('spec-server', ['jasmine::build', 'connect:spec:keepalive']); 70 | 71 | // Default task. 72 | grunt.registerTask('default', ['jshint', 'jasmine']); 73 | 74 | }; 75 | -------------------------------------------------------------------------------- /backbone.fetch-cache.min.js: -------------------------------------------------------------------------------- 1 | /* backbone-fetch-cache v2.0.2 (2017-07-11) 2 | by MadGlory (http://madglory.com) - https://github.com/madglory/backbone-fetch-cache.git 3 | */ 4 | !function(a,b){"function"==typeof define&&define.amd?define(["underscore","backbone","jquery"],function(_,Backbone,c){return a.Backbone=b(_,Backbone,c)}):"undefined"!=typeof exports&&"undefined"!=typeof require?module.exports=b(require("underscore"),require("backbone"),require("jquery")):a.Backbone=b(a._,a.Backbone,a.jQuery)}(this,function(_,Backbone,a){function b(b,c){if(b&&_.isObject(b)){if(_.isFunction(b.getCacheKey))return b.getCacheKey(c);b=c&&c.url?c.url:_.isFunction(b.url)?b.url():b.url}else if(_.isFunction(b))return b(c);return c&&c.data?"string"==typeof c.data?b+"?"+c.data:b+"?"+a.param(c.data):b}function c(a,b,c){b=b||{};var d=Backbone.fetchCache.getCacheKey(a,b),e=!1,f=b.lastSync||(new Date).getTime(),g=!1;d&&b.cache!==!1&&(b.cache||b.prefill)&&(b.expires!==!1&&(e=(new Date).getTime()+1e3*(b.expires||300)),b.prefillExpires!==!1&&(g=(new Date).getTime()+1e3*(b.prefillExpires||300)),Backbone.fetchCache._cache[d]={expires:e,lastSync:f,prefillExpires:g,value:c},Backbone.fetchCache.setLocalStorage())}function d(a,c){return _.isFunction(a)?a=a():a&&_.isObject(a)&&(a=b(a,c)),Backbone.fetchCache._cache[a]}function e(a,b){return d(a).lastSync}function f(a,c){_.isFunction(a)?a=a():a&&_.isObject(a)&&(a=b(a,c)),delete Backbone.fetchCache._cache[a],Backbone.fetchCache.setLocalStorage()}function g(){Backbone.fetchCache._cache={}}function h(){if(l&&Backbone.fetchCache.localStorage)try{localStorage.setItem(Backbone.fetchCache.getLocalStorageKey(),JSON.stringify(Backbone.fetchCache._cache))}catch(a){var b=a.code||a.number||a.message;if(22!==b&&1014!==b)throw a;this._deleteCacheWithPriority()}}function i(){if(l&&Backbone.fetchCache.localStorage){var a=localStorage.getItem(Backbone.fetchCache.getLocalStorageKey())||"{}";Backbone.fetchCache._cache=JSON.parse(a)}}function j(a){return window.setTimeout(a,0)}var k={modelFetch:Backbone.Model.prototype.fetch,modelSync:Backbone.Model.prototype.sync,collectionFetch:Backbone.Collection.prototype.fetch},l=function(){try{localStorage.setItem("test_support","test_support"),localStorage.removeItem("test_support")}catch(a){return!1}return!0}();return Backbone.fetchCache=Backbone.fetchCache||{},Backbone.fetchCache._cache=Backbone.fetchCache._cache||{},Backbone.fetchCache.enabled=!0,Backbone.fetchCache.priorityFn=function(a,b){return a&&a.expires&&b&&b.expires?a.expires-b.expires:a},Backbone.fetchCache._prioritize=function(){var a=_.values(this._cache).sort(this.priorityFn),b=_.indexOf(_.values(this._cache),a[0]);return _.keys(this._cache)[b]},Backbone.fetchCache._deleteCacheWithPriority=function(){Backbone.fetchCache._cache[this._prioritize()]=null,delete Backbone.fetchCache._cache[this._prioritize()],Backbone.fetchCache.setLocalStorage()},Backbone.fetchCache.getLocalStorageKey=function(){return"backboneCache"},"undefined"==typeof Backbone.fetchCache.localStorage&&(Backbone.fetchCache.localStorage=!0),Backbone.Model.prototype.fetch=function(b){function c(){return b.prefill&&(!b.prefillExpires||i)}function e(){b.parse&&(l=o.parse(l,b)),o.set(l,b),_.isFunction(b.prefillSuccess)&&b.prefillSuccess.call(n,o,l,b),o.trigger("cachesync",o,l,b),o.trigger("sync",o,l,b),c()?m.notifyWith(n,[o]):(_.isFunction(b.success)&&b.success.call(n,o,l,b),m.resolveWith(n,[o]))}if(!Backbone.fetchCache.enabled)return k.modelFetch.apply(this,arguments);b=_.defaults(b||{},{parse:!0});var f=Backbone.fetchCache.getCacheKey(this,b),g=d(f),h=!1,i=!1,l=!1,m=new a.Deferred,n=b.context||this,o=this;if(g&&(h=g.expires,h=h&&g.expires<(new Date).getTime(),i=g.prefillExpires,i=i&&g.prefillExpires<(new Date).getTime(),l=g.value),!h&&(b.cache||b.prefill)&&l&&(null==b.async&&(b.async=!0),b.async?j(e):e(),!c()))return m.promise();var p=k.modelFetch.apply(this,arguments);return p.done(_.bind(m.resolve,n,this)).done(_.bind(Backbone.fetchCache.setCache,null,this,b)).fail(_.bind(m.reject,n,this)),m.abort=p.abort,m.promise()},Backbone.Model.prototype.sync=function(a,b,c){if("read"===a||!Backbone.fetchCache.enabled)return k.modelSync.apply(this,arguments);var d,e,g=b.collection,h=[];for(h.push(Backbone.fetchCache.getCacheKey(b,c)),g&&h.push(Backbone.fetchCache.getCacheKey(g)),d=0,e=h.length;e>d;d++)f(h[d]);return k.modelSync.apply(this,arguments)},Backbone.Collection.prototype.fetch=function(b){function c(){return b.prefill&&(!b.prefillExpires||i)}function e(){o[b.reset?"reset":"set"](l,b),_.isFunction(b.prefillSuccess)&&b.prefillSuccess.call(n,o),o.trigger("cachesync",o,l,b),o.trigger("sync",o,l,b),c()?m.notifyWith(n,[o]):(_.isFunction(b.success)&&b.success.call(n,o,l,b),m.resolveWith(n,[o]))}if(!Backbone.fetchCache.enabled)return k.collectionFetch.apply(this,arguments);b=_.defaults(b||{},{parse:!0});var f=Backbone.fetchCache.getCacheKey(this,b),g=d(f),h=!1,i=!1,l=!1,m=new a.Deferred,n=b.context||this,o=this;if(g&&(h=g.expires,h=h&&g.expires<(new Date).getTime(),i=g.prefillExpires,i=i&&g.prefillExpires<(new Date).getTime(),l=g.value),!h&&(b.cache||b.prefill)&&l&&(null==b.async&&(b.async=!0),b.async?j(e):e(),!c()))return m.promise();var p=k.collectionFetch.apply(this,arguments);return p.done(_.bind(m.resolve,n,this)).done(_.bind(Backbone.fetchCache.setCache,null,this,b)).fail(_.bind(m.reject,n,this)),m.abort=p.abort,m.promise()},i(),Backbone.fetchCache._superMethods=k,Backbone.fetchCache.setCache=c,Backbone.fetchCache.getCache=d,Backbone.fetchCache.getCacheKey=b,Backbone.fetchCache.getLastSync=e,Backbone.fetchCache.clearItem=f,Backbone.fetchCache.reset=g,Backbone.fetchCache.setLocalStorage=h,Backbone.fetchCache.getLocalStorage=i,Backbone}); -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Backbone fetch cache 2 | 3 | [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/madglory/backbone-fetch-cache?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 4 | 5 | [![Build Status](https://travis-ci.org/madglory/backbone-fetch-cache.png?branch=master)](https://travis-ci.org/madglory/backbone-fetch-cache) 6 | 7 | A Backbone plugin to cache calls to `Backbone.Model.prototype.fetch` and 8 | `Backbone.Collection.prototype.fetch` in memory and `localStorage`. 9 | 10 | Compatible with Backbone 1.0.0 and up. 11 | 12 | ## How it works 13 | This plugin intercepts calls to `fetch` and stores the results in a cache object (`Backbone.fetchCache._cache`). If fetch is called with `{ cache: true }` in the options and the URL has already been cached the AJAX call will be skipped. 14 | 15 | The local cache is persisted in `localStorage` if available for faster initial page loads. 16 | 17 | The `prefill` option allows for models and collections to be filled with cache data just until the `fetch` operations are complete -- a nice way to make the app feel snappy on slower connections. 18 | 19 | __*What's wrong with browser caching for AJAX responses?*__ 20 | Nothing. This plugin is primarily for working with an API where you don't have control over response cache headers. 21 | 22 | ## Usage 23 | Add the script to the page after backbone.js has been included: 24 | 25 | ```html 26 | 27 | 28 | ``` 29 | 30 | or if you're using AMD, require the script as a module: 31 | 32 | ```js 33 | require(['path/to/backbone.fetch-cache.js']); 34 | ``` 35 | 36 | Note that the AMD module depends on `underscore` and `backbone` modules being defined as it lists them as dependencies. If you don't have these mapped, you can do it by adding the following to your require config: 37 | 38 | ```js 39 | requirejs.config({ 40 | paths: { 41 | backbone: 'actual/path/to/backbone.js', 42 | underscore: 'actual/path/to/underscore.js' 43 | } 44 | }); 45 | ``` 46 | 47 | If you are using CommonJS modules, install via `npm`: 48 | 49 | ``` 50 | npm install backbone-fetch-cache 51 | ``` 52 | 53 | then require it in your modules: 54 | 55 | ```js 56 | var fetchCache = require('backbone-fetch-cache'); 57 | ``` 58 | 59 | A note on [Zepto.js](http://zeptojs.com/). This plugin uses `jQuery.Deferred` 60 | which is not included in Zepto. You'll need to add a third party 61 | implementation of `jQuery.Deferred`, e.g. [Standalone-Deferred](https://github.com/Mumakil/Standalone-Deferred) 62 | 63 | ## API 64 | ### `#.fetch() options` 65 | The most used API hook for Backbone Fetch Cache is the Model and Collection `#.fetch()` method. Here are the options you can pass into that method to get behaviour particular to Backbone Fetch Cache: 66 | 67 | #### `cache` 68 | Calls to `modelInstance.fetch` or `collectionInstance.fetch` will be fulfilled from the cache (if possible) when `cache: true` is set in the options hash: 69 | 70 | ```js 71 | myModel.fetch({ cache: true }); 72 | myCollection.fetch({ cache: true }); 73 | ``` 74 | 75 | #### `expires` 76 | Cache values expire after 5 minutes by default. You can adjust this by passing 77 | `expires: ` to the fetch call. Set to `false` to never expire: 78 | 79 | ```js 80 | myModel.fetch({ cache: true, expires: 60000 }); 81 | myCollection.fetch({ cache: true, expires: 60000 }); 82 | 83 | // These will never expire 84 | myModel.fetch({ cache: true, expires: false }); 85 | myCollection.fetch({ cache: true, expires: false }); 86 | ``` 87 | 88 | #### `prefill` and `prefillExpires` 89 | This option allows the model/collection to be populated from the cache immediately and then be updated once the call to `fetch` has completed. The initial cache hit calls the `prefillSuccess` callback and then the AJAX success/error callbacks are called as normal when the request is complete. This allows the page to render something immediately and then update it after the request completes. (Note: the `prefillSuccess` callback _will not fire_ if the data is not found in the cache.) 90 | 91 | ```js 92 | myModel.fetch({ 93 | prefill: true, 94 | prefillSuccess: someCallback, // Fires when the cache hit happens 95 | success: anotherCallback // Fires after the AJAX call 96 | }); 97 | 98 | myCollection.fetch({ 99 | prefill: true, 100 | prefillSuccess: someCallback, // Fires when the cache hit happens 101 | success: anotherCallback // Fires after the AJAX call 102 | }); 103 | ``` 104 | 105 | `prefill` and `prefillExpires` options can be used with the promises interface like so (note: the `progress` event _will not fire_ if the data is not found in the cache.): 106 | 107 | ```js 108 | var modelPromise = myModel.fetch({ prefill: true }); 109 | modelPromise.progress(someCallback); // Fires when the cache hit happens 110 | modelPromise.done(anotherCallback); // Fires after the AJAX call 111 | 112 | var collectionPromise = myModel.fetch({ prefill: true }); 113 | collectionPromise.progress(someCallback); // Fires when the cache hit happens 114 | collectionPromise.done(anotherCallback); // Fires after the AJAX call 115 | ``` 116 | 117 | `prefillExpires` affects prefill in the following ways: 118 | 119 | 1. If the cache doesn't hold the requested data, just fetch it (usual behaviour) 120 | 2. If the cache holds an expired version of the requested data, just fetch it (usual behaviour) 121 | 3. If the cache holds requested data that is neither expired nor prefill expired, just return it and don't do a fetch / prefill callback (usual cache behavior, unusual prefill behaviour) 122 | 3. If the cache holds requested data that isn't expired but is prefill expired, use the prefill callback and do a fetch (usual prefill behaviour) 123 | 124 | ```js 125 | myModel.fetch({ 126 | prefill: true, 127 | prefillExpires: 2000, 128 | prefillSuccess: someCallback, // Fires when the cache hit happens 129 | success: anotherCallback // Fires after the AJAX call 130 | }); 131 | 132 | myCollection.fetch({ 133 | prefill: true, 134 | prefillExpires: 2000, 135 | prefillSuccess: someCallback, // Fires when the cache hit happens 136 | success: anotherCallback // Fires after the AJAX call 137 | }); 138 | ``` 139 | 140 | ### lastSync 141 | If you want to know when was the last (server) sync of a given key, you can use: 142 | 143 | ```js 144 | Backbone.fetchCache.getLastSync(myKey); 145 | ``` 146 | 147 | ### Explicitly fetching a cached item 148 | You can explicitly fetch a cached item, without having to call the models/collection `fetch`. This might be useful for debugging and testing: 149 | 150 | ```js 151 | Backbone.fetchCache.getCache(myKey); 152 | ``` 153 | 154 | This will return the raw cache entity. Usually, you'd probably want to get the value, which is the model/collection data (attributes) itself: 155 | 156 | ```js 157 | Backbone.fetchCache.getCache(myKey).value; 158 | ``` 159 | Note that this method always gets the cache data, without validating it or checking if it expired. 160 | 161 | ### localStorage 162 | By default the cache is persisted in localStorage (if available). Set `Backbone.fetchCache.localStorage = false` to disable this: 163 | 164 | ```js 165 | Backbone.fetchCache.localStorage = false; 166 | ``` 167 | 168 | ### Custom cache keys 169 | 170 | By default the cache key is generated from the model's `url` property and the requests params: 171 | 172 | ```js 173 | '/model/1?some=param' 174 | ``` 175 | 176 | This can be overridden with custom logic if required: 177 | ```js 178 | // Instance is a Backbone.Model or Backbone.Collection, options are passed 179 | // through form the fetch call 180 | Backbone.fetchCache.getCacheKey = function(instance, options) { 181 | return instance.constructor.name + ':' + instance.get('id'); 182 | // => UserModel:1 183 | }; 184 | ``` 185 | 186 | You can also define a custom cache key function per model/collection 187 | ```js 188 | var MyModel = Backbone.Model.extend({ 189 | ... 190 | getCacheKey: function(options) { 191 | return 'myModel:' + this.get('id'); 192 | } 193 | // => myModel:1 194 | 195 | }); 196 | ``` 197 | 198 | ### Cache Priority in localStorage 199 | When setting items in localStorage, the browser may throw a ```QUOTA_EXCEEDED_ERR```, meaning the store is full. Backbone.fetchCache tries to work around this problem by deleting what it considers the most stale item to make space for the new data. The staleness of data is determined by the sorting function `priorityFn`, which by default returns the oldest item. 200 | 201 | The default is: 202 | ``` 203 | Backbone.fetchCache.priorityFn = function(a, b) { 204 | if (!a || !a.expires || !b || !b.expires) { 205 | return a; 206 | } 207 | 208 | return a.expires - b.expires; 209 | }; 210 | ``` 211 | 212 | You can override this function with your own logic (in this case, returning the most recent item): 213 | ``` 214 | Backbone.fetchCache.priorityFn = function(a, b) { 215 | return b.expires - a.expires; 216 | }; 217 | ``` 218 | 219 | ### Events 220 | 221 | The `sync` event will be triggered on a server response which skips the cache, as well as a cache hit. A `cachesync` event is also triggered on Models and Collections, but only when a cache hit happens, not a server sync. This can be used if you need to differentiate between a server backed `sync` event and a cache backed event. 222 | 223 | ### Automatic Cache Invalidation 224 | The cache item for a particular call will be cleared when a `create`, `update`, `patch` or `delete` call is made to the server. The plugin tries to be intelligent about this by clearing a model's collection cache if the model has a `.collection property`. 225 | 226 | To achieve this, the plugin overrides `Backbone.Model.protoype.sync` and then calls the original method. If you are planning to override sync on a particular model then you should keep this in mind and make sure that you do it before the plugin runs. Overriding Backbone.sync directly should work fine. 227 | 228 | ### Manual Cache Invalidation 229 | Sometimes you just need to clear a cached item manually. `Backbone.fetchCache.clearItem()` can be called safely from anywhere in your application. It will take your backbone Model or Collection, a function that returns the key String, or the key String itself. If you pass in a Model or Collection, the `.getCacheKey()` method will be checked before the `url` property. 230 | 231 | ```js 232 | // With Model 233 | Backbone.fetchCache.clearItem(myModel); 234 | // With Function 235 | Backbone.fetchCache.clearItem(function () { 236 | return someModel.url; 237 | }); 238 | // With Key 239 | Backbone.fetchCache.clearItem(myModel.url); 240 | ``` 241 | 242 | ## Tests 243 | You can run the tests by cloning the repo, installing the dependencies and 244 | running `grunt jasmine`: 245 | 246 | ``` 247 | $ npm install 248 | $ grunt jasmine 249 | ``` 250 | 251 | The default grunt task runs tests and lints the code. 252 | 253 | ``` 254 | $ grunt 255 | ``` 256 | 257 | ## Releases 258 | We will handle release versioning based on the changes. This will update `package.json`, `bower.json`, and also create a new git tag. 259 | 260 | Once the version is bumped you can uglify the file so the version makes it into the uglified version. 261 | 262 | ``` 263 | $ grunt uglify 264 | ``` 265 | 266 | Now commit the changes, push to GitHub, and `npm publish`. 267 | -------------------------------------------------------------------------------- /backbone.fetch-cache.js: -------------------------------------------------------------------------------- 1 | /*! 2 | backbone.fetch-cache v2.0.2 3 | by Andy Appleton - https://github.com/mrappleton/backbone-fetch-cache.git 4 | */ 5 | 6 | // AMD wrapper from https://github.com/umdjs/umd/blob/master/amdWebGlobal.js 7 | 8 | (function (root, factory) { 9 | if (typeof define === 'function' && define.amd) { 10 | // AMD. Register as an anonymous module and set browser global 11 | define(['underscore', 'backbone', 'jquery'], function (_, Backbone, $) { 12 | return (root.Backbone = factory(_, Backbone, $)); 13 | }); 14 | } else if (typeof exports !== 'undefined' && typeof require !== 'undefined') { 15 | module.exports = factory(require('underscore'), require('backbone'), require('jquery')); 16 | } else { 17 | // Browser globals 18 | root.Backbone = factory(root._, root.Backbone, root.jQuery); 19 | } 20 | }(this, function (_, Backbone, $) { 21 | 22 | // Setup 23 | var superMethods = { 24 | modelFetch: Backbone.Model.prototype.fetch, 25 | modelSync: Backbone.Model.prototype.sync, 26 | collectionFetch: Backbone.Collection.prototype.fetch 27 | }, 28 | supportLocalStorage = (function() { 29 | try { 30 | // impossible to write on some platforms when private browsing is on and 31 | // throws an exception = local storage not supported. 32 | localStorage.setItem('test_support', 'test_support'); 33 | localStorage.removeItem('test_support'); 34 | } catch (e) { 35 | return false; 36 | } 37 | 38 | return true; 39 | })(); 40 | 41 | Backbone.fetchCache = (Backbone.fetchCache || {}); 42 | Backbone.fetchCache._cache = (Backbone.fetchCache._cache || {}); 43 | // Global flag to enable/disable caching 44 | Backbone.fetchCache.enabled = true; 45 | 46 | Backbone.fetchCache.priorityFn = function(a, b) { 47 | if (!a || !a.expires || !b || !b.expires) { 48 | return a; 49 | } 50 | 51 | return a.expires - b.expires; 52 | }; 53 | 54 | Backbone.fetchCache._prioritize = function() { 55 | var sorted = _.values(this._cache).sort(this.priorityFn); 56 | var index = _.indexOf(_.values(this._cache), sorted[0]); 57 | return _.keys(this._cache)[index]; 58 | }; 59 | 60 | Backbone.fetchCache._deleteCacheWithPriority = function() { 61 | Backbone.fetchCache._cache[this._prioritize()] = null; 62 | delete Backbone.fetchCache._cache[this._prioritize()]; 63 | Backbone.fetchCache.setLocalStorage(); 64 | }; 65 | 66 | Backbone.fetchCache.getLocalStorageKey = function() { 67 | return 'backboneCache'; 68 | }; 69 | 70 | if (typeof Backbone.fetchCache.localStorage === 'undefined') { 71 | Backbone.fetchCache.localStorage = true; 72 | } 73 | 74 | // Shared methods 75 | function getCacheKey(key, opts) { 76 | if (key && _.isObject(key)) { 77 | // If the model has its own, custom, cache key function, use it. 78 | if (_.isFunction(key.getCacheKey)) { 79 | return key.getCacheKey(opts); 80 | } 81 | // else, use the URL 82 | if (opts && opts.url) { 83 | key = opts.url; 84 | } else { 85 | key = _.isFunction(key.url) ? key.url() : key.url; 86 | } 87 | } else if (_.isFunction(key)) { 88 | return key(opts); 89 | } 90 | if (opts && opts.data) { 91 | if(typeof opts.data === 'string') { 92 | return key + '?' + opts.data; 93 | } else { 94 | return key + '?' + $.param(opts.data); 95 | } 96 | } 97 | return key; 98 | } 99 | 100 | function setCache(instance, opts, attrs) { 101 | opts = (opts || {}); 102 | var key = Backbone.fetchCache.getCacheKey(instance, opts), 103 | expires = false, 104 | lastSync = (opts.lastSync || (new Date()).getTime()), 105 | prefillExpires = false; 106 | 107 | // Need url to use as cache key so return if we can't get it 108 | if (!key) { return; } 109 | 110 | // Never set the cache if user has explicitly said not to 111 | if (opts.cache === false) { return; } 112 | 113 | // Don't set the cache unless cache: true or prefill: true option is passed 114 | if (!(opts.cache || opts.prefill)) { return; } 115 | 116 | if (opts.expires !== false) { 117 | expires = (new Date()).getTime() + ((opts.expires || 5 * 60) * 1000); 118 | } 119 | 120 | if (opts.prefillExpires !== false) { 121 | prefillExpires = (new Date()).getTime() + ((opts.prefillExpires || 5 * 60) * 1000); 122 | } 123 | 124 | Backbone.fetchCache._cache[key] = { 125 | expires: expires, 126 | lastSync : lastSync, 127 | prefillExpires: prefillExpires, 128 | value: attrs 129 | }; 130 | 131 | Backbone.fetchCache.setLocalStorage(); 132 | } 133 | 134 | function getCache(key, opts) { 135 | if (_.isFunction(key)) { 136 | key = key(); 137 | } else if (key && _.isObject(key)) { 138 | key = getCacheKey(key, opts); 139 | } 140 | 141 | return Backbone.fetchCache._cache[key]; 142 | } 143 | 144 | function getLastSync(key, opts) { 145 | return getCache(key).lastSync; 146 | } 147 | 148 | function clearItem(key, opts) { 149 | if (_.isFunction(key)) { 150 | key = key(); 151 | } else if (key && _.isObject(key)) { 152 | key = getCacheKey(key, opts); 153 | } 154 | delete Backbone.fetchCache._cache[key]; 155 | Backbone.fetchCache.setLocalStorage(); 156 | } 157 | 158 | function reset() { 159 | // Clearing all cache items 160 | Backbone.fetchCache._cache = {}; 161 | } 162 | 163 | function setLocalStorage() { 164 | if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; } 165 | try { 166 | localStorage.setItem(Backbone.fetchCache.getLocalStorageKey(), JSON.stringify(Backbone.fetchCache._cache)); 167 | } catch (err) { 168 | var code = err.code || err.number || err.message; 169 | if (code === 22 || code === 1014) { 170 | this._deleteCacheWithPriority(); 171 | } else { 172 | throw(err); 173 | } 174 | } 175 | } 176 | 177 | function getLocalStorage() { 178 | if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; } 179 | var json = localStorage.getItem(Backbone.fetchCache.getLocalStorageKey()) || '{}'; 180 | Backbone.fetchCache._cache = JSON.parse(json); 181 | } 182 | 183 | function nextTick(fn) { 184 | return window.setTimeout(fn, 0); 185 | } 186 | 187 | // Instance methods 188 | Backbone.Model.prototype.fetch = function(opts) { 189 | //Bypass caching if it's not enabled 190 | if(!Backbone.fetchCache.enabled) { 191 | return superMethods.modelFetch.apply(this, arguments); 192 | } 193 | opts = _.defaults(opts || {}, { parse: true }); 194 | var key = Backbone.fetchCache.getCacheKey(this, opts), 195 | data = getCache(key), 196 | expired = false, 197 | prefillExpired = false, 198 | attributes = false, 199 | deferred = new $.Deferred(), 200 | context = opts.context || this, 201 | self = this; 202 | 203 | function isPrefilling() { 204 | return opts.prefill && (!opts.prefillExpires || prefillExpired); 205 | } 206 | 207 | function setData() { 208 | if (opts.parse) { 209 | attributes = self.parse(attributes, opts); 210 | } 211 | 212 | self.set(attributes, opts); 213 | if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess.call(context, self, attributes, opts); } 214 | 215 | // Trigger sync events 216 | self.trigger('cachesync', self, attributes, opts); 217 | self.trigger('sync', self, attributes, opts); 218 | 219 | // Notify progress if we're still waiting for an AJAX call to happen... 220 | if (isPrefilling()) { deferred.notifyWith(context, [self]); } 221 | // ...finish and return if we're not 222 | else { 223 | if (_.isFunction(opts.success)) { opts.success.call(context, self, attributes, opts); } 224 | deferred.resolveWith(context, [self]); 225 | } 226 | } 227 | 228 | if (data) { 229 | expired = data.expires; 230 | expired = expired && data.expires < (new Date()).getTime(); 231 | prefillExpired = data.prefillExpires; 232 | prefillExpired = prefillExpired && data.prefillExpires < (new Date()).getTime(); 233 | attributes = data.value; 234 | } 235 | 236 | if (!expired && (opts.cache || opts.prefill) && attributes) { 237 | // Ensure that cache resolution adhers to async option, defaults to true. 238 | if (opts.async == null) { opts.async = true; } 239 | 240 | if (opts.async) { 241 | nextTick(setData); 242 | } else { 243 | setData(); 244 | } 245 | 246 | if (!isPrefilling()) { 247 | return deferred.promise(); 248 | } 249 | } 250 | 251 | // Delegate to the actual fetch method and store the attributes in the cache 252 | var jqXHR = superMethods.modelFetch.apply(this, arguments); 253 | // resolve the returned promise when the AJAX call completes 254 | jqXHR.done( _.bind(deferred.resolve, context, this) ) 255 | // Set the new data in the cache 256 | .done( _.bind(Backbone.fetchCache.setCache, null, this, opts) ) 257 | // Reject the promise on fail 258 | .fail( _.bind(deferred.reject, context, this) ); 259 | 260 | deferred.abort = jqXHR.abort; 261 | 262 | // return a promise which provides the same methods as a jqXHR object 263 | return deferred.promise(); 264 | }; 265 | 266 | // Override Model.prototype.sync and try to clear cache items if it looks 267 | // like they are being updated. 268 | Backbone.Model.prototype.sync = function(method, model, options) { 269 | // Only empty the cache if we're doing a create, update, patch or delete. 270 | // or caching is not enabled 271 | if (method === 'read' || !Backbone.fetchCache.enabled) { 272 | return superMethods.modelSync.apply(this, arguments); 273 | } 274 | 275 | var collection = model.collection, 276 | keys = [], 277 | i, len; 278 | 279 | // Build up a list of keys to delete from the cache, starting with this 280 | keys.push(Backbone.fetchCache.getCacheKey(model, options)); 281 | 282 | // If this model has a collection, also try to delete the cache for that 283 | if (!!collection) { 284 | keys.push(Backbone.fetchCache.getCacheKey(collection)); 285 | } 286 | 287 | // Empty cache for all found keys 288 | for (i = 0, len = keys.length; i < len; i++) { clearItem(keys[i]); } 289 | 290 | return superMethods.modelSync.apply(this, arguments); 291 | }; 292 | 293 | Backbone.Collection.prototype.fetch = function(opts) { 294 | // Bypass caching if it's not enabled 295 | if(!Backbone.fetchCache.enabled) { 296 | return superMethods.collectionFetch.apply(this, arguments); 297 | } 298 | 299 | opts = _.defaults(opts || {}, { parse: true }); 300 | var key = Backbone.fetchCache.getCacheKey(this, opts), 301 | data = getCache(key), 302 | expired = false, 303 | prefillExpired = false, 304 | attributes = false, 305 | deferred = new $.Deferred(), 306 | context = opts.context || this, 307 | self = this; 308 | 309 | function isPrefilling() { 310 | return opts.prefill && (!opts.prefillExpires || prefillExpired); 311 | } 312 | 313 | function setData() { 314 | self[opts.reset ? 'reset' : 'set'](attributes, opts); 315 | if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess.call(context, self); } 316 | 317 | // Trigger sync events 318 | self.trigger('cachesync', self, attributes, opts); 319 | self.trigger('sync', self, attributes, opts); 320 | 321 | // Notify progress if we're still waiting for an AJAX call to happen... 322 | if (isPrefilling()) { deferred.notifyWith(context, [self]); } 323 | // ...finish and return if we're not 324 | else { 325 | if (_.isFunction(opts.success)) { opts.success.call(context, self, attributes, opts); } 326 | deferred.resolveWith(context, [self]); 327 | } 328 | } 329 | 330 | if (data) { 331 | expired = data.expires; 332 | expired = expired && data.expires < (new Date()).getTime(); 333 | prefillExpired = data.prefillExpires; 334 | prefillExpired = prefillExpired && data.prefillExpires < (new Date()).getTime(); 335 | attributes = data.value; 336 | } 337 | 338 | if (!expired && (opts.cache || opts.prefill) && attributes) { 339 | // Ensure that cache resolution adhers to async option, defaults to true. 340 | if (opts.async == null) { opts.async = true; } 341 | 342 | if (opts.async) { 343 | nextTick(setData); 344 | } else { 345 | setData(); 346 | } 347 | 348 | if (!isPrefilling()) { 349 | return deferred.promise(); 350 | } 351 | } 352 | 353 | // Delegate to the actual fetch method and store the attributes in the cache 354 | var jqXHR = superMethods.collectionFetch.apply(this, arguments); 355 | // resolve the returned promise when the AJAX call completes 356 | jqXHR.done( _.bind(deferred.resolve, context, this) ) 357 | // Set the new data in the cache 358 | .done( _.bind(Backbone.fetchCache.setCache, null, this, opts) ) 359 | // Reject the promise on fail 360 | .fail( _.bind(deferred.reject, context, this) ); 361 | 362 | deferred.abort = jqXHR.abort; 363 | 364 | // return a promise which provides the same methods as a jqXHR object 365 | return deferred.promise(); 366 | }; 367 | 368 | // Prime the cache from localStorage on initialization 369 | getLocalStorage(); 370 | 371 | // Exports 372 | 373 | Backbone.fetchCache._superMethods = superMethods; 374 | Backbone.fetchCache.setCache = setCache; 375 | Backbone.fetchCache.getCache = getCache; 376 | Backbone.fetchCache.getCacheKey = getCacheKey; 377 | Backbone.fetchCache.getLastSync = getLastSync; 378 | Backbone.fetchCache.clearItem = clearItem; 379 | Backbone.fetchCache.reset = reset; 380 | Backbone.fetchCache.setLocalStorage = setLocalStorage; 381 | Backbone.fetchCache.getLocalStorage = getLocalStorage; 382 | 383 | return Backbone; 384 | })); 385 | -------------------------------------------------------------------------------- /spec/lib/underscore.js: -------------------------------------------------------------------------------- 1 | // Underscore.js 1.4.3 2 | // http://underscorejs.org 3 | // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. 4 | // Underscore may be freely distributed under the MIT license. 5 | 6 | (function() { 7 | 8 | // Baseline setup 9 | // -------------- 10 | 11 | // Establish the root object, `window` in the browser, or `global` on the server. 12 | var root = this; 13 | 14 | // Save the previous value of the `_` variable. 15 | var previousUnderscore = root._; 16 | 17 | // Establish the object that gets returned to break out of a loop iteration. 18 | var breaker = {}; 19 | 20 | // Save bytes in the minified (but not gzipped) version: 21 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; 22 | 23 | // Create quick reference variables for speed access to core prototypes. 24 | var push = ArrayProto.push, 25 | slice = ArrayProto.slice, 26 | concat = ArrayProto.concat, 27 | toString = ObjProto.toString, 28 | hasOwnProperty = ObjProto.hasOwnProperty; 29 | 30 | // All **ECMAScript 5** native function implementations that we hope to use 31 | // are declared here. 32 | var 33 | nativeForEach = ArrayProto.forEach, 34 | nativeMap = ArrayProto.map, 35 | nativeReduce = ArrayProto.reduce, 36 | nativeReduceRight = ArrayProto.reduceRight, 37 | nativeFilter = ArrayProto.filter, 38 | nativeEvery = ArrayProto.every, 39 | nativeSome = ArrayProto.some, 40 | nativeIndexOf = ArrayProto.indexOf, 41 | nativeLastIndexOf = ArrayProto.lastIndexOf, 42 | nativeIsArray = Array.isArray, 43 | nativeKeys = Object.keys, 44 | nativeBind = FuncProto.bind; 45 | 46 | // Create a safe reference to the Underscore object for use below. 47 | var _ = function(obj) { 48 | if (obj instanceof _) return obj; 49 | if (!(this instanceof _)) return new _(obj); 50 | this._wrapped = obj; 51 | }; 52 | 53 | // Export the Underscore object for **Node.js**, with 54 | // backwards-compatibility for the old `require()` API. If we're in 55 | // the browser, add `_` as a global object via a string identifier, 56 | // for Closure Compiler "advanced" mode. 57 | if (typeof exports !== 'undefined') { 58 | if (typeof module !== 'undefined' && module.exports) { 59 | exports = module.exports = _; 60 | } 61 | exports._ = _; 62 | } else { 63 | root._ = _; 64 | } 65 | 66 | // Current version. 67 | _.VERSION = '1.4.3'; 68 | 69 | // Collection Functions 70 | // -------------------- 71 | 72 | // The cornerstone, an `each` implementation, aka `forEach`. 73 | // Handles objects with the built-in `forEach`, arrays, and raw objects. 74 | // Delegates to **ECMAScript 5**'s native `forEach` if available. 75 | var each = _.each = _.forEach = function(obj, iterator, context) { 76 | if (obj == null) return; 77 | if (nativeForEach && obj.forEach === nativeForEach) { 78 | obj.forEach(iterator, context); 79 | } else if (obj.length === +obj.length) { 80 | for (var i = 0, l = obj.length; i < l; i++) { 81 | if (iterator.call(context, obj[i], i, obj) === breaker) return; 82 | } 83 | } else { 84 | for (var key in obj) { 85 | if (_.has(obj, key)) { 86 | if (iterator.call(context, obj[key], key, obj) === breaker) return; 87 | } 88 | } 89 | } 90 | }; 91 | 92 | // Return the results of applying the iterator to each element. 93 | // Delegates to **ECMAScript 5**'s native `map` if available. 94 | _.map = _.collect = function(obj, iterator, context) { 95 | var results = []; 96 | if (obj == null) return results; 97 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); 98 | each(obj, function(value, index, list) { 99 | results[results.length] = iterator.call(context, value, index, list); 100 | }); 101 | return results; 102 | }; 103 | 104 | var reduceError = 'Reduce of empty array with no initial value'; 105 | 106 | // **Reduce** builds up a single result from a list of values, aka `inject`, 107 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. 108 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { 109 | var initial = arguments.length > 2; 110 | if (obj == null) obj = []; 111 | if (nativeReduce && obj.reduce === nativeReduce) { 112 | if (context) iterator = _.bind(iterator, context); 113 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); 114 | } 115 | each(obj, function(value, index, list) { 116 | if (!initial) { 117 | memo = value; 118 | initial = true; 119 | } else { 120 | memo = iterator.call(context, memo, value, index, list); 121 | } 122 | }); 123 | if (!initial) throw new TypeError(reduceError); 124 | return memo; 125 | }; 126 | 127 | // The right-associative version of reduce, also known as `foldr`. 128 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available. 129 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) { 130 | var initial = arguments.length > 2; 131 | if (obj == null) obj = []; 132 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { 133 | if (context) iterator = _.bind(iterator, context); 134 | return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); 135 | } 136 | var length = obj.length; 137 | if (length !== +length) { 138 | var keys = _.keys(obj); 139 | length = keys.length; 140 | } 141 | each(obj, function(value, index, list) { 142 | index = keys ? keys[--length] : --length; 143 | if (!initial) { 144 | memo = obj[index]; 145 | initial = true; 146 | } else { 147 | memo = iterator.call(context, memo, obj[index], index, list); 148 | } 149 | }); 150 | if (!initial) throw new TypeError(reduceError); 151 | return memo; 152 | }; 153 | 154 | // Return the first value which passes a truth test. Aliased as `detect`. 155 | _.find = _.detect = function(obj, iterator, context) { 156 | var result; 157 | any(obj, function(value, index, list) { 158 | if (iterator.call(context, value, index, list)) { 159 | result = value; 160 | return true; 161 | } 162 | }); 163 | return result; 164 | }; 165 | 166 | // Return all the elements that pass a truth test. 167 | // Delegates to **ECMAScript 5**'s native `filter` if available. 168 | // Aliased as `select`. 169 | _.filter = _.select = function(obj, iterator, context) { 170 | var results = []; 171 | if (obj == null) return results; 172 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); 173 | each(obj, function(value, index, list) { 174 | if (iterator.call(context, value, index, list)) results[results.length] = value; 175 | }); 176 | return results; 177 | }; 178 | 179 | // Return all the elements for which a truth test fails. 180 | _.reject = function(obj, iterator, context) { 181 | return _.filter(obj, function(value, index, list) { 182 | return !iterator.call(context, value, index, list); 183 | }, context); 184 | }; 185 | 186 | // Determine whether all of the elements match a truth test. 187 | // Delegates to **ECMAScript 5**'s native `every` if available. 188 | // Aliased as `all`. 189 | _.every = _.all = function(obj, iterator, context) { 190 | iterator || (iterator = _.identity); 191 | var result = true; 192 | if (obj == null) return result; 193 | if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); 194 | each(obj, function(value, index, list) { 195 | if (!(result = result && iterator.call(context, value, index, list))) return breaker; 196 | }); 197 | return !!result; 198 | }; 199 | 200 | // Determine if at least one element in the object matches a truth test. 201 | // Delegates to **ECMAScript 5**'s native `some` if available. 202 | // Aliased as `any`. 203 | var any = _.some = _.any = function(obj, iterator, context) { 204 | iterator || (iterator = _.identity); 205 | var result = false; 206 | if (obj == null) return result; 207 | if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); 208 | each(obj, function(value, index, list) { 209 | if (result || (result = iterator.call(context, value, index, list))) return breaker; 210 | }); 211 | return !!result; 212 | }; 213 | 214 | // Determine if the array or object contains a given value (using `===`). 215 | // Aliased as `include`. 216 | _.contains = _.include = function(obj, target) { 217 | if (obj == null) return false; 218 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; 219 | return any(obj, function(value) { 220 | return value === target; 221 | }); 222 | }; 223 | 224 | // Invoke a method (with arguments) on every item in a collection. 225 | _.invoke = function(obj, method) { 226 | var args = slice.call(arguments, 2); 227 | return _.map(obj, function(value) { 228 | return (_.isFunction(method) ? method : value[method]).apply(value, args); 229 | }); 230 | }; 231 | 232 | // Convenience version of a common use case of `map`: fetching a property. 233 | _.pluck = function(obj, key) { 234 | return _.map(obj, function(value){ return value[key]; }); 235 | }; 236 | 237 | // Convenience version of a common use case of `filter`: selecting only objects 238 | // with specific `key:value` pairs. 239 | _.where = function(obj, attrs) { 240 | if (_.isEmpty(attrs)) return []; 241 | return _.filter(obj, function(value) { 242 | for (var key in attrs) { 243 | if (attrs[key] !== value[key]) return false; 244 | } 245 | return true; 246 | }); 247 | }; 248 | 249 | // Return the maximum element or (element-based computation). 250 | // Can't optimize arrays of integers longer than 65,535 elements. 251 | // See: https://bugs.webkit.org/show_bug.cgi?id=80797 252 | _.max = function(obj, iterator, context) { 253 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 254 | return Math.max.apply(Math, obj); 255 | } 256 | if (!iterator && _.isEmpty(obj)) return -Infinity; 257 | var result = {computed : -Infinity, value: -Infinity}; 258 | each(obj, function(value, index, list) { 259 | var computed = iterator ? iterator.call(context, value, index, list) : value; 260 | computed >= result.computed && (result = {value : value, computed : computed}); 261 | }); 262 | return result.value; 263 | }; 264 | 265 | // Return the minimum element (or element-based computation). 266 | _.min = function(obj, iterator, context) { 267 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 268 | return Math.min.apply(Math, obj); 269 | } 270 | if (!iterator && _.isEmpty(obj)) return Infinity; 271 | var result = {computed : Infinity, value: Infinity}; 272 | each(obj, function(value, index, list) { 273 | var computed = iterator ? iterator.call(context, value, index, list) : value; 274 | computed < result.computed && (result = {value : value, computed : computed}); 275 | }); 276 | return result.value; 277 | }; 278 | 279 | // Shuffle an array. 280 | _.shuffle = function(obj) { 281 | var rand; 282 | var index = 0; 283 | var shuffled = []; 284 | each(obj, function(value) { 285 | rand = _.random(index++); 286 | shuffled[index - 1] = shuffled[rand]; 287 | shuffled[rand] = value; 288 | }); 289 | return shuffled; 290 | }; 291 | 292 | // An internal function to generate lookup iterators. 293 | var lookupIterator = function(value) { 294 | return _.isFunction(value) ? value : function(obj){ return obj[value]; }; 295 | }; 296 | 297 | // Sort the object's values by a criterion produced by an iterator. 298 | _.sortBy = function(obj, value, context) { 299 | var iterator = lookupIterator(value); 300 | return _.pluck(_.map(obj, function(value, index, list) { 301 | return { 302 | value : value, 303 | index : index, 304 | criteria : iterator.call(context, value, index, list) 305 | }; 306 | }).sort(function(left, right) { 307 | var a = left.criteria; 308 | var b = right.criteria; 309 | if (a !== b) { 310 | if (a > b || a === void 0) return 1; 311 | if (a < b || b === void 0) return -1; 312 | } 313 | return left.index < right.index ? -1 : 1; 314 | }), 'value'); 315 | }; 316 | 317 | // An internal function used for aggregate "group by" operations. 318 | var group = function(obj, value, context, behavior) { 319 | var result = {}; 320 | var iterator = lookupIterator(value || _.identity); 321 | each(obj, function(value, index) { 322 | var key = iterator.call(context, value, index, obj); 323 | behavior(result, key, value); 324 | }); 325 | return result; 326 | }; 327 | 328 | // Groups the object's values by a criterion. Pass either a string attribute 329 | // to group by, or a function that returns the criterion. 330 | _.groupBy = function(obj, value, context) { 331 | return group(obj, value, context, function(result, key, value) { 332 | (_.has(result, key) ? result[key] : (result[key] = [])).push(value); 333 | }); 334 | }; 335 | 336 | // Counts instances of an object that group by a certain criterion. Pass 337 | // either a string attribute to count by, or a function that returns the 338 | // criterion. 339 | _.countBy = function(obj, value, context) { 340 | return group(obj, value, context, function(result, key) { 341 | if (!_.has(result, key)) result[key] = 0; 342 | result[key]++; 343 | }); 344 | }; 345 | 346 | // Use a comparator function to figure out the smallest index at which 347 | // an object should be inserted so as to maintain order. Uses binary search. 348 | _.sortedIndex = function(array, obj, iterator, context) { 349 | iterator = iterator == null ? _.identity : lookupIterator(iterator); 350 | var value = iterator.call(context, obj); 351 | var low = 0, high = array.length; 352 | while (low < high) { 353 | var mid = (low + high) >>> 1; 354 | iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; 355 | } 356 | return low; 357 | }; 358 | 359 | // Safely convert anything iterable into a real, live array. 360 | _.toArray = function(obj) { 361 | if (!obj) return []; 362 | if (_.isArray(obj)) return slice.call(obj); 363 | if (obj.length === +obj.length) return _.map(obj, _.identity); 364 | return _.values(obj); 365 | }; 366 | 367 | // Return the number of elements in an object. 368 | _.size = function(obj) { 369 | if (obj == null) return 0; 370 | return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; 371 | }; 372 | 373 | // Array Functions 374 | // --------------- 375 | 376 | // Get the first element of an array. Passing **n** will return the first N 377 | // values in the array. Aliased as `head` and `take`. The **guard** check 378 | // allows it to work with `_.map`. 379 | _.first = _.head = _.take = function(array, n, guard) { 380 | if (array == null) return void 0; 381 | return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; 382 | }; 383 | 384 | // Returns everything but the last entry of the array. Especially useful on 385 | // the arguments object. Passing **n** will return all the values in 386 | // the array, excluding the last N. The **guard** check allows it to work with 387 | // `_.map`. 388 | _.initial = function(array, n, guard) { 389 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); 390 | }; 391 | 392 | // Get the last element of an array. Passing **n** will return the last N 393 | // values in the array. The **guard** check allows it to work with `_.map`. 394 | _.last = function(array, n, guard) { 395 | if (array == null) return void 0; 396 | if ((n != null) && !guard) { 397 | return slice.call(array, Math.max(array.length - n, 0)); 398 | } else { 399 | return array[array.length - 1]; 400 | } 401 | }; 402 | 403 | // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. 404 | // Especially useful on the arguments object. Passing an **n** will return 405 | // the rest N values in the array. The **guard** 406 | // check allows it to work with `_.map`. 407 | _.rest = _.tail = _.drop = function(array, n, guard) { 408 | return slice.call(array, (n == null) || guard ? 1 : n); 409 | }; 410 | 411 | // Trim out all falsy values from an array. 412 | _.compact = function(array) { 413 | return _.filter(array, _.identity); 414 | }; 415 | 416 | // Internal implementation of a recursive `flatten` function. 417 | var flatten = function(input, shallow, output) { 418 | each(input, function(value) { 419 | if (_.isArray(value)) { 420 | shallow ? push.apply(output, value) : flatten(value, shallow, output); 421 | } else { 422 | output.push(value); 423 | } 424 | }); 425 | return output; 426 | }; 427 | 428 | // Return a completely flattened version of an array. 429 | _.flatten = function(array, shallow) { 430 | return flatten(array, shallow, []); 431 | }; 432 | 433 | // Return a version of the array that does not contain the specified value(s). 434 | _.without = function(array) { 435 | return _.difference(array, slice.call(arguments, 1)); 436 | }; 437 | 438 | // Produce a duplicate-free version of the array. If the array has already 439 | // been sorted, you have the option of using a faster algorithm. 440 | // Aliased as `unique`. 441 | _.uniq = _.unique = function(array, isSorted, iterator, context) { 442 | if (_.isFunction(isSorted)) { 443 | context = iterator; 444 | iterator = isSorted; 445 | isSorted = false; 446 | } 447 | var initial = iterator ? _.map(array, iterator, context) : array; 448 | var results = []; 449 | var seen = []; 450 | each(initial, function(value, index) { 451 | if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { 452 | seen.push(value); 453 | results.push(array[index]); 454 | } 455 | }); 456 | return results; 457 | }; 458 | 459 | // Produce an array that contains the union: each distinct element from all of 460 | // the passed-in arrays. 461 | _.union = function() { 462 | return _.uniq(concat.apply(ArrayProto, arguments)); 463 | }; 464 | 465 | // Produce an array that contains every item shared between all the 466 | // passed-in arrays. 467 | _.intersection = function(array) { 468 | var rest = slice.call(arguments, 1); 469 | return _.filter(_.uniq(array), function(item) { 470 | return _.every(rest, function(other) { 471 | return _.indexOf(other, item) >= 0; 472 | }); 473 | }); 474 | }; 475 | 476 | // Take the difference between one array and a number of other arrays. 477 | // Only the elements present in just the first array will remain. 478 | _.difference = function(array) { 479 | var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); 480 | return _.filter(array, function(value){ return !_.contains(rest, value); }); 481 | }; 482 | 483 | // Zip together multiple lists into a single array -- elements that share 484 | // an index go together. 485 | _.zip = function() { 486 | var args = slice.call(arguments); 487 | var length = _.max(_.pluck(args, 'length')); 488 | var results = new Array(length); 489 | for (var i = 0; i < length; i++) { 490 | results[i] = _.pluck(args, "" + i); 491 | } 492 | return results; 493 | }; 494 | 495 | // Converts lists into objects. Pass either a single array of `[key, value]` 496 | // pairs, or two parallel arrays of the same length -- one of keys, and one of 497 | // the corresponding values. 498 | _.object = function(list, values) { 499 | if (list == null) return {}; 500 | var result = {}; 501 | for (var i = 0, l = list.length; i < l; i++) { 502 | if (values) { 503 | result[list[i]] = values[i]; 504 | } else { 505 | result[list[i][0]] = list[i][1]; 506 | } 507 | } 508 | return result; 509 | }; 510 | 511 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), 512 | // we need this function. Return the position of the first occurrence of an 513 | // item in an array, or -1 if the item is not included in the array. 514 | // Delegates to **ECMAScript 5**'s native `indexOf` if available. 515 | // If the array is large and already in sort order, pass `true` 516 | // for **isSorted** to use binary search. 517 | _.indexOf = function(array, item, isSorted) { 518 | if (array == null) return -1; 519 | var i = 0, l = array.length; 520 | if (isSorted) { 521 | if (typeof isSorted == 'number') { 522 | i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); 523 | } else { 524 | i = _.sortedIndex(array, item); 525 | return array[i] === item ? i : -1; 526 | } 527 | } 528 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); 529 | for (; i < l; i++) if (array[i] === item) return i; 530 | return -1; 531 | }; 532 | 533 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. 534 | _.lastIndexOf = function(array, item, from) { 535 | if (array == null) return -1; 536 | var hasIndex = from != null; 537 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { 538 | return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); 539 | } 540 | var i = (hasIndex ? from : array.length); 541 | while (i--) if (array[i] === item) return i; 542 | return -1; 543 | }; 544 | 545 | // Generate an integer Array containing an arithmetic progression. A port of 546 | // the native Python `range()` function. See 547 | // [the Python documentation](http://docs.python.org/library/functions.html#range). 548 | _.range = function(start, stop, step) { 549 | if (arguments.length <= 1) { 550 | stop = start || 0; 551 | start = 0; 552 | } 553 | step = arguments[2] || 1; 554 | 555 | var len = Math.max(Math.ceil((stop - start) / step), 0); 556 | var idx = 0; 557 | var range = new Array(len); 558 | 559 | while(idx < len) { 560 | range[idx++] = start; 561 | start += step; 562 | } 563 | 564 | return range; 565 | }; 566 | 567 | // Function (ahem) Functions 568 | // ------------------ 569 | 570 | // Reusable constructor function for prototype setting. 571 | var ctor = function(){}; 572 | 573 | // Create a function bound to a given object (assigning `this`, and arguments, 574 | // optionally). Binding with arguments is also known as `curry`. 575 | // Delegates to **ECMAScript 5**'s native `Function.bind` if available. 576 | // We check for `func.bind` first, to fail fast when `func` is undefined. 577 | _.bind = function(func, context) { 578 | var args, bound; 579 | if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); 580 | if (!_.isFunction(func)) throw new TypeError; 581 | args = slice.call(arguments, 2); 582 | return bound = function() { 583 | if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); 584 | ctor.prototype = func.prototype; 585 | var self = new ctor; 586 | ctor.prototype = null; 587 | var result = func.apply(self, args.concat(slice.call(arguments))); 588 | if (Object(result) === result) return result; 589 | return self; 590 | }; 591 | }; 592 | 593 | // Bind all of an object's methods to that object. Useful for ensuring that 594 | // all callbacks defined on an object belong to it. 595 | _.bindAll = function(obj) { 596 | var funcs = slice.call(arguments, 1); 597 | if (funcs.length == 0) funcs = _.functions(obj); 598 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); 599 | return obj; 600 | }; 601 | 602 | // Memoize an expensive function by storing its results. 603 | _.memoize = function(func, hasher) { 604 | var memo = {}; 605 | hasher || (hasher = _.identity); 606 | return function() { 607 | var key = hasher.apply(this, arguments); 608 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); 609 | }; 610 | }; 611 | 612 | // Delays a function for the given number of milliseconds, and then calls 613 | // it with the arguments supplied. 614 | _.delay = function(func, wait) { 615 | var args = slice.call(arguments, 2); 616 | return setTimeout(function(){ return func.apply(null, args); }, wait); 617 | }; 618 | 619 | // Defers a function, scheduling it to run after the current call stack has 620 | // cleared. 621 | _.defer = function(func) { 622 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); 623 | }; 624 | 625 | // Returns a function, that, when invoked, will only be triggered at most once 626 | // during a given window of time. 627 | _.throttle = function(func, wait) { 628 | var context, args, timeout, result; 629 | var previous = 0; 630 | var later = function() { 631 | previous = new Date; 632 | timeout = null; 633 | result = func.apply(context, args); 634 | }; 635 | return function() { 636 | var now = new Date; 637 | var remaining = wait - (now - previous); 638 | context = this; 639 | args = arguments; 640 | if (remaining <= 0) { 641 | clearTimeout(timeout); 642 | timeout = null; 643 | previous = now; 644 | result = func.apply(context, args); 645 | } else if (!timeout) { 646 | timeout = setTimeout(later, remaining); 647 | } 648 | return result; 649 | }; 650 | }; 651 | 652 | // Returns a function, that, as long as it continues to be invoked, will not 653 | // be triggered. The function will be called after it stops being called for 654 | // N milliseconds. If `immediate` is passed, trigger the function on the 655 | // leading edge, instead of the trailing. 656 | _.debounce = function(func, wait, immediate) { 657 | var timeout, result; 658 | return function() { 659 | var context = this, args = arguments; 660 | var later = function() { 661 | timeout = null; 662 | if (!immediate) result = func.apply(context, args); 663 | }; 664 | var callNow = immediate && !timeout; 665 | clearTimeout(timeout); 666 | timeout = setTimeout(later, wait); 667 | if (callNow) result = func.apply(context, args); 668 | return result; 669 | }; 670 | }; 671 | 672 | // Returns a function that will be executed at most one time, no matter how 673 | // often you call it. Useful for lazy initialization. 674 | _.once = function(func) { 675 | var ran = false, memo; 676 | return function() { 677 | if (ran) return memo; 678 | ran = true; 679 | memo = func.apply(this, arguments); 680 | func = null; 681 | return memo; 682 | }; 683 | }; 684 | 685 | // Returns the first function passed as an argument to the second, 686 | // allowing you to adjust arguments, run code before and after, and 687 | // conditionally execute the original function. 688 | _.wrap = function(func, wrapper) { 689 | return function() { 690 | var args = [func]; 691 | push.apply(args, arguments); 692 | return wrapper.apply(this, args); 693 | }; 694 | }; 695 | 696 | // Returns a function that is the composition of a list of functions, each 697 | // consuming the return value of the function that follows. 698 | _.compose = function() { 699 | var funcs = arguments; 700 | return function() { 701 | var args = arguments; 702 | for (var i = funcs.length - 1; i >= 0; i--) { 703 | args = [funcs[i].apply(this, args)]; 704 | } 705 | return args[0]; 706 | }; 707 | }; 708 | 709 | // Returns a function that will only be executed after being called N times. 710 | _.after = function(times, func) { 711 | if (times <= 0) return func(); 712 | return function() { 713 | if (--times < 1) { 714 | return func.apply(this, arguments); 715 | } 716 | }; 717 | }; 718 | 719 | // Object Functions 720 | // ---------------- 721 | 722 | // Retrieve the names of an object's properties. 723 | // Delegates to **ECMAScript 5**'s native `Object.keys` 724 | _.keys = nativeKeys || function(obj) { 725 | if (obj !== Object(obj)) throw new TypeError('Invalid object'); 726 | var keys = []; 727 | for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; 728 | return keys; 729 | }; 730 | 731 | // Retrieve the values of an object's properties. 732 | _.values = function(obj) { 733 | var values = []; 734 | for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); 735 | return values; 736 | }; 737 | 738 | // Convert an object into a list of `[key, value]` pairs. 739 | _.pairs = function(obj) { 740 | var pairs = []; 741 | for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); 742 | return pairs; 743 | }; 744 | 745 | // Invert the keys and values of an object. The values must be serializable. 746 | _.invert = function(obj) { 747 | var result = {}; 748 | for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; 749 | return result; 750 | }; 751 | 752 | // Return a sorted list of the function names available on the object. 753 | // Aliased as `methods` 754 | _.functions = _.methods = function(obj) { 755 | var names = []; 756 | for (var key in obj) { 757 | if (_.isFunction(obj[key])) names.push(key); 758 | } 759 | return names.sort(); 760 | }; 761 | 762 | // Extend a given object with all the properties in passed-in object(s). 763 | _.extend = function(obj) { 764 | each(slice.call(arguments, 1), function(source) { 765 | if (source) { 766 | for (var prop in source) { 767 | obj[prop] = source[prop]; 768 | } 769 | } 770 | }); 771 | return obj; 772 | }; 773 | 774 | // Return a copy of the object only containing the whitelisted properties. 775 | _.pick = function(obj) { 776 | var copy = {}; 777 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 778 | each(keys, function(key) { 779 | if (key in obj) copy[key] = obj[key]; 780 | }); 781 | return copy; 782 | }; 783 | 784 | // Return a copy of the object without the blacklisted properties. 785 | _.omit = function(obj) { 786 | var copy = {}; 787 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 788 | for (var key in obj) { 789 | if (!_.contains(keys, key)) copy[key] = obj[key]; 790 | } 791 | return copy; 792 | }; 793 | 794 | // Fill in a given object with default properties. 795 | _.defaults = function(obj) { 796 | each(slice.call(arguments, 1), function(source) { 797 | if (source) { 798 | for (var prop in source) { 799 | if (obj[prop] == null) obj[prop] = source[prop]; 800 | } 801 | } 802 | }); 803 | return obj; 804 | }; 805 | 806 | // Create a (shallow-cloned) duplicate of an object. 807 | _.clone = function(obj) { 808 | if (!_.isObject(obj)) return obj; 809 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 810 | }; 811 | 812 | // Invokes interceptor with the obj, and then returns obj. 813 | // The primary purpose of this method is to "tap into" a method chain, in 814 | // order to perform operations on intermediate results within the chain. 815 | _.tap = function(obj, interceptor) { 816 | interceptor(obj); 817 | return obj; 818 | }; 819 | 820 | // Internal recursive comparison function for `isEqual`. 821 | var eq = function(a, b, aStack, bStack) { 822 | // Identical objects are equal. `0 === -0`, but they aren't identical. 823 | // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. 824 | if (a === b) return a !== 0 || 1 / a == 1 / b; 825 | // A strict comparison is necessary because `null == undefined`. 826 | if (a == null || b == null) return a === b; 827 | // Unwrap any wrapped objects. 828 | if (a instanceof _) a = a._wrapped; 829 | if (b instanceof _) b = b._wrapped; 830 | // Compare `[[Class]]` names. 831 | var className = toString.call(a); 832 | if (className != toString.call(b)) return false; 833 | switch (className) { 834 | // Strings, numbers, dates, and booleans are compared by value. 835 | case '[object String]': 836 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 837 | // equivalent to `new String("5")`. 838 | return a == String(b); 839 | case '[object Number]': 840 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 841 | // other numeric values. 842 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); 843 | case '[object Date]': 844 | case '[object Boolean]': 845 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 846 | // millisecond representations. Note that invalid dates with millisecond representations 847 | // of `NaN` are not equivalent. 848 | return +a == +b; 849 | // RegExps are compared by their source patterns and flags. 850 | case '[object RegExp]': 851 | return a.source == b.source && 852 | a.global == b.global && 853 | a.multiline == b.multiline && 854 | a.ignoreCase == b.ignoreCase; 855 | } 856 | if (typeof a != 'object' || typeof b != 'object') return false; 857 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 858 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 859 | var length = aStack.length; 860 | while (length--) { 861 | // Linear search. Performance is inversely proportional to the number of 862 | // unique nested structures. 863 | if (aStack[length] == a) return bStack[length] == b; 864 | } 865 | // Add the first object to the stack of traversed objects. 866 | aStack.push(a); 867 | bStack.push(b); 868 | var size = 0, result = true; 869 | // Recursively compare objects and arrays. 870 | if (className == '[object Array]') { 871 | // Compare array lengths to determine if a deep comparison is necessary. 872 | size = a.length; 873 | result = size == b.length; 874 | if (result) { 875 | // Deep compare the contents, ignoring non-numeric properties. 876 | while (size--) { 877 | if (!(result = eq(a[size], b[size], aStack, bStack))) break; 878 | } 879 | } 880 | } else { 881 | // Objects with different constructors are not equivalent, but `Object`s 882 | // from different frames are. 883 | var aCtor = a.constructor, bCtor = b.constructor; 884 | if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && 885 | _.isFunction(bCtor) && (bCtor instanceof bCtor))) { 886 | return false; 887 | } 888 | // Deep compare objects. 889 | for (var key in a) { 890 | if (_.has(a, key)) { 891 | // Count the expected number of properties. 892 | size++; 893 | // Deep compare each member. 894 | if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; 895 | } 896 | } 897 | // Ensure that both objects contain the same number of properties. 898 | if (result) { 899 | for (key in b) { 900 | if (_.has(b, key) && !(size--)) break; 901 | } 902 | result = !size; 903 | } 904 | } 905 | // Remove the first object from the stack of traversed objects. 906 | aStack.pop(); 907 | bStack.pop(); 908 | return result; 909 | }; 910 | 911 | // Perform a deep comparison to check if two objects are equal. 912 | _.isEqual = function(a, b) { 913 | return eq(a, b, [], []); 914 | }; 915 | 916 | // Is a given array, string, or object empty? 917 | // An "empty" object has no enumerable own-properties. 918 | _.isEmpty = function(obj) { 919 | if (obj == null) return true; 920 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; 921 | for (var key in obj) if (_.has(obj, key)) return false; 922 | return true; 923 | }; 924 | 925 | // Is a given value a DOM element? 926 | _.isElement = function(obj) { 927 | return !!(obj && obj.nodeType === 1); 928 | }; 929 | 930 | // Is a given value an array? 931 | // Delegates to ECMA5's native Array.isArray 932 | _.isArray = nativeIsArray || function(obj) { 933 | return toString.call(obj) == '[object Array]'; 934 | }; 935 | 936 | // Is a given variable an object? 937 | _.isObject = function(obj) { 938 | return obj === Object(obj); 939 | }; 940 | 941 | // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. 942 | each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { 943 | _['is' + name] = function(obj) { 944 | return toString.call(obj) == '[object ' + name + ']'; 945 | }; 946 | }); 947 | 948 | // Define a fallback version of the method in browsers (ahem, IE), where 949 | // there isn't any inspectable "Arguments" type. 950 | if (!_.isArguments(arguments)) { 951 | _.isArguments = function(obj) { 952 | return !!(obj && _.has(obj, 'callee')); 953 | }; 954 | } 955 | 956 | // Optimize `isFunction` if appropriate. 957 | if (typeof (/./) !== 'function') { 958 | _.isFunction = function(obj) { 959 | return typeof obj === 'function'; 960 | }; 961 | } 962 | 963 | // Is a given object a finite number? 964 | _.isFinite = function(obj) { 965 | return isFinite(obj) && !isNaN(parseFloat(obj)); 966 | }; 967 | 968 | // Is the given value `NaN`? (NaN is the only number which does not equal itself). 969 | _.isNaN = function(obj) { 970 | return _.isNumber(obj) && obj != +obj; 971 | }; 972 | 973 | // Is a given value a boolean? 974 | _.isBoolean = function(obj) { 975 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; 976 | }; 977 | 978 | // Is a given value equal to null? 979 | _.isNull = function(obj) { 980 | return obj === null; 981 | }; 982 | 983 | // Is a given variable undefined? 984 | _.isUndefined = function(obj) { 985 | return obj === void 0; 986 | }; 987 | 988 | // Shortcut function for checking if an object has a given property directly 989 | // on itself (in other words, not on a prototype). 990 | _.has = function(obj, key) { 991 | return hasOwnProperty.call(obj, key); 992 | }; 993 | 994 | // Utility Functions 995 | // ----------------- 996 | 997 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 998 | // previous owner. Returns a reference to the Underscore object. 999 | _.noConflict = function() { 1000 | root._ = previousUnderscore; 1001 | return this; 1002 | }; 1003 | 1004 | // Keep the identity function around for default iterators. 1005 | _.identity = function(value) { 1006 | return value; 1007 | }; 1008 | 1009 | // Run a function **n** times. 1010 | _.times = function(n, iterator, context) { 1011 | var accum = Array(n); 1012 | for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); 1013 | return accum; 1014 | }; 1015 | 1016 | // Return a random integer between min and max (inclusive). 1017 | _.random = function(min, max) { 1018 | if (max == null) { 1019 | max = min; 1020 | min = 0; 1021 | } 1022 | return min + (0 | Math.random() * (max - min + 1)); 1023 | }; 1024 | 1025 | // List of HTML entities for escaping. 1026 | var entityMap = { 1027 | escape: { 1028 | '&': '&', 1029 | '<': '<', 1030 | '>': '>', 1031 | '"': '"', 1032 | "'": ''', 1033 | '/': '/' 1034 | } 1035 | }; 1036 | entityMap.unescape = _.invert(entityMap.escape); 1037 | 1038 | // Regexes containing the keys and values listed immediately above. 1039 | var entityRegexes = { 1040 | escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), 1041 | unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') 1042 | }; 1043 | 1044 | // Functions for escaping and unescaping strings to/from HTML interpolation. 1045 | _.each(['escape', 'unescape'], function(method) { 1046 | _[method] = function(string) { 1047 | if (string == null) return ''; 1048 | return ('' + string).replace(entityRegexes[method], function(match) { 1049 | return entityMap[method][match]; 1050 | }); 1051 | }; 1052 | }); 1053 | 1054 | // If the value of the named property is a function then invoke it; 1055 | // otherwise, return it. 1056 | _.result = function(object, property) { 1057 | if (object == null) return null; 1058 | var value = object[property]; 1059 | return _.isFunction(value) ? value.call(object) : value; 1060 | }; 1061 | 1062 | // Add your own custom functions to the Underscore object. 1063 | _.mixin = function(obj) { 1064 | each(_.functions(obj), function(name){ 1065 | var func = _[name] = obj[name]; 1066 | _.prototype[name] = function() { 1067 | var args = [this._wrapped]; 1068 | push.apply(args, arguments); 1069 | return result.call(this, func.apply(_, args)); 1070 | }; 1071 | }); 1072 | }; 1073 | 1074 | // Generate a unique integer id (unique within the entire client session). 1075 | // Useful for temporary DOM ids. 1076 | var idCounter = 0; 1077 | _.uniqueId = function(prefix) { 1078 | var id = '' + ++idCounter; 1079 | return prefix ? prefix + id : id; 1080 | }; 1081 | 1082 | // By default, Underscore uses ERB-style template delimiters, change the 1083 | // following template settings to use alternative delimiters. 1084 | _.templateSettings = { 1085 | evaluate : /<%([\s\S]+?)%>/g, 1086 | interpolate : /<%=([\s\S]+?)%>/g, 1087 | escape : /<%-([\s\S]+?)%>/g 1088 | }; 1089 | 1090 | // When customizing `templateSettings`, if you don't want to define an 1091 | // interpolation, evaluation or escaping regex, we need one that is 1092 | // guaranteed not to match. 1093 | var noMatch = /(.)^/; 1094 | 1095 | // Certain characters need to be escaped so that they can be put into a 1096 | // string literal. 1097 | var escapes = { 1098 | "'": "'", 1099 | '\\': '\\', 1100 | '\r': 'r', 1101 | '\n': 'n', 1102 | '\t': 't', 1103 | '\u2028': 'u2028', 1104 | '\u2029': 'u2029' 1105 | }; 1106 | 1107 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; 1108 | 1109 | // JavaScript micro-templating, similar to John Resig's implementation. 1110 | // Underscore templating handles arbitrary delimiters, preserves whitespace, 1111 | // and correctly escapes quotes within interpolated code. 1112 | _.template = function(text, data, settings) { 1113 | settings = _.defaults({}, settings, _.templateSettings); 1114 | 1115 | // Combine delimiters into one regular expression via alternation. 1116 | var matcher = new RegExp([ 1117 | (settings.escape || noMatch).source, 1118 | (settings.interpolate || noMatch).source, 1119 | (settings.evaluate || noMatch).source 1120 | ].join('|') + '|$', 'g'); 1121 | 1122 | // Compile the template source, escaping string literals appropriately. 1123 | var index = 0; 1124 | var source = "__p+='"; 1125 | text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { 1126 | source += text.slice(index, offset) 1127 | .replace(escaper, function(match) { return '\\' + escapes[match]; }); 1128 | 1129 | if (escape) { 1130 | source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; 1131 | } 1132 | if (interpolate) { 1133 | source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; 1134 | } 1135 | if (evaluate) { 1136 | source += "';\n" + evaluate + "\n__p+='"; 1137 | } 1138 | index = offset + match.length; 1139 | return match; 1140 | }); 1141 | source += "';\n"; 1142 | 1143 | // If a variable is not specified, place data values in local scope. 1144 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; 1145 | 1146 | source = "var __t,__p='',__j=Array.prototype.join," + 1147 | "print=function(){__p+=__j.call(arguments,'');};\n" + 1148 | source + "return __p;\n"; 1149 | 1150 | try { 1151 | var render = new Function(settings.variable || 'obj', '_', source); 1152 | } catch (e) { 1153 | e.source = source; 1154 | throw e; 1155 | } 1156 | 1157 | if (data) return render(data, _); 1158 | var template = function(data) { 1159 | return render.call(this, data, _); 1160 | }; 1161 | 1162 | // Provide the compiled function source as a convenience for precompilation. 1163 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; 1164 | 1165 | return template; 1166 | }; 1167 | 1168 | // Add a "chain" function, which will delegate to the wrapper. 1169 | _.chain = function(obj) { 1170 | return _(obj).chain(); 1171 | }; 1172 | 1173 | // OOP 1174 | // --------------- 1175 | // If Underscore is called as a function, it returns a wrapped object that 1176 | // can be used OO-style. This wrapper holds altered versions of all the 1177 | // underscore functions. Wrapped objects may be chained. 1178 | 1179 | // Helper function to continue chaining intermediate results. 1180 | var result = function(obj) { 1181 | return this._chain ? _(obj).chain() : obj; 1182 | }; 1183 | 1184 | // Add all of the Underscore functions to the wrapper object. 1185 | _.mixin(_); 1186 | 1187 | // Add all mutator Array functions to the wrapper. 1188 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 1189 | var method = ArrayProto[name]; 1190 | _.prototype[name] = function() { 1191 | var obj = this._wrapped; 1192 | method.apply(obj, arguments); 1193 | if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; 1194 | return result.call(this, obj); 1195 | }; 1196 | }); 1197 | 1198 | // Add all accessor Array functions to the wrapper. 1199 | each(['concat', 'join', 'slice'], function(name) { 1200 | var method = ArrayProto[name]; 1201 | _.prototype[name] = function() { 1202 | return result.call(this, method.apply(this._wrapped, arguments)); 1203 | }; 1204 | }); 1205 | 1206 | _.extend(_.prototype, { 1207 | 1208 | // Start chaining a wrapped Underscore object. 1209 | chain: function() { 1210 | this._chain = true; 1211 | return this; 1212 | }, 1213 | 1214 | // Extracts the result from a wrapped and chained object. 1215 | value: function() { 1216 | return this._wrapped; 1217 | } 1218 | 1219 | }); 1220 | 1221 | }).call(this); -------------------------------------------------------------------------------- /spec/backbone.fetch-cache.spec.js: -------------------------------------------------------------------------------- 1 | describe('Backbone.fetchCache', function() { 2 | var model, errorModel, collection, errorCollection, server, modelResponse, errorModelResponse, collectionResponse; 3 | var originalPriorityFn = Backbone.fetchCache.priorityFn; 4 | 5 | // Async spec waitsFor helpers 6 | function promiseComplete(promise) { 7 | return function() { 8 | return promise.state() !== 'pending'; 9 | }; 10 | } 11 | 12 | function promiseNotified(promise) { 13 | var notified = false; 14 | 15 | promise.progress(function() { 16 | notified = true; 17 | }); 18 | 19 | return function() { 20 | return notified; 21 | }; 22 | } 23 | 24 | beforeEach(function() { 25 | model = new Backbone.Model(); 26 | model.url = '/model-cache-test'; 27 | errorModel = new Backbone.Model(); 28 | errorModel.url = '/model-error-cache-test'; 29 | collection = new Backbone.Collection(); 30 | collection.url = '/collection-cache-test'; 31 | errorCollection = new Backbone.Collection(); 32 | errorCollection.url = '/collection-error-cache-test'; 33 | 34 | // Mock xhr resposes 35 | server = sinon.fakeServer.create(); 36 | modelResponse = { sausages: 'bacon' }; 37 | collectionResponse = [{ sausages: 'bacon' }, { rice: 'peas' }]; 38 | server.respondWith('GET', model.url, [ 39 | 200, 40 | { 'Content-Type': 'application/json' }, 41 | JSON.stringify(modelResponse) 42 | ]); 43 | server.respondWith('GET', collection.url, [ 44 | 200, 45 | { 'Content-Type': 'application/json' }, 46 | JSON.stringify(collectionResponse) 47 | ]); 48 | server.respondWith('GET', errorModel.url, [ 49 | 500, 50 | { 'Content-Type': 'test/html' }, 51 | 'Server Error' 52 | ]); 53 | server.respondWith('GET', errorCollection.url, [ 54 | 500, 55 | { 'Content-Type': 'test/html' }, 56 | 'Server Error' 57 | ]); 58 | }); 59 | 60 | afterEach(function() { 61 | Backbone.fetchCache._cache = {}; 62 | localStorage.clear('backboneCache'); 63 | Backbone.fetchCache.priorityFn = originalPriorityFn; 64 | server.restore(); 65 | }); 66 | 67 | describe('AMD', function() { 68 | it('defines an AMD module if supported', function() { 69 | var s = document.createElement('script'); 70 | s.src = '/backbone.fetch-cache.js'; 71 | 72 | window.define = jasmine.createSpy('AMD define'); 73 | window.define.amd = true; 74 | 75 | s.onload = function(){ 76 | expect(window.define).toHaveBeenCalled(); 77 | }; 78 | 79 | document.body.appendChild(s); 80 | }); 81 | }); 82 | 83 | describe('.getCacheKey', function() { 84 | it('uses options url with priority if set', function() { 85 | expect(Backbone.fetchCache.getCacheKey(model, {url: '/options-test-url'})) 86 | .toEqual('/options-test-url'); 87 | }); 88 | 89 | it('uses model url if options url is not set', function() { 90 | expect(Backbone.fetchCache.getCacheKey(model, {})) 91 | .toEqual(model.url); 92 | }); 93 | 94 | it('generates a standard querystring', function() { 95 | var value = { 96 | 'string': 'stringValue', 97 | 'float': 2.1, 98 | 'bool':false 99 | }; 100 | var expected = model.url + '?string=stringValue&float=2.1&bool=false'; 101 | expect(Backbone.fetchCache.getCacheKey(model, {data: value})) 102 | .toEqual(expected); 103 | }); 104 | 105 | it('generates a standard querystring if data is a string', function() { 106 | var value = 'test'; 107 | var expected = model.url + '?test'; 108 | expect(Backbone.fetchCache.getCacheKey(model, {data: value})) 109 | .toEqual(expected); 110 | }); 111 | }); 112 | 113 | describe('custom cache key', function() { 114 | var customModel; 115 | beforeEach(function() { 116 | customModel = new (Backbone.Model.extend({ 117 | getCacheKey: function(options) { 118 | return 'cache_token'; 119 | } 120 | }))(); 121 | }); 122 | 123 | it('fetches correct cache key', function() { 124 | expect(Backbone.fetchCache.getCacheKey(customModel)) 125 | .toEqual('cache_token'); 126 | }); 127 | }); 128 | 129 | describe('.setCache', function() { 130 | var opts; 131 | 132 | beforeEach(function() { 133 | opts = { cache: true }; 134 | }); 135 | 136 | it('noops if the instance does not have a url', function() { 137 | model.url = null; 138 | Backbone.fetchCache.setCache(model, opts, modelResponse); 139 | expect(Backbone.fetchCache._cache[model.url]).toBeUndefined(); 140 | }); 141 | 142 | it('noops unless cache: true is passed', function() { 143 | Backbone.fetchCache.setCache(model, null, modelResponse); 144 | expect(Backbone.fetchCache._cache[model.url]).toBeUndefined(); 145 | }); 146 | 147 | it('keys cache items by the getCacheKey method',function() { 148 | spyOn(Backbone.fetchCache, 'getCacheKey').andReturn('someCacheKey'); 149 | Backbone.fetchCache.setCache(model, opts, modelResponse); 150 | expect(Backbone.fetchCache._cache['someCacheKey'].value) 151 | .toEqual(modelResponse); 152 | }); 153 | 154 | it('calls setLocalStorage', function() { 155 | spyOn(Backbone.fetchCache, 'setLocalStorage'); 156 | Backbone.fetchCache.setCache(model, opts); 157 | expect(Backbone.fetchCache.setLocalStorage).toHaveBeenCalled(); 158 | }); 159 | 160 | describe('with prefill: true option', function() { 161 | beforeEach(function() { 162 | opts = { prefill: true }; 163 | }); 164 | 165 | it('caches even if cache: true is not passed', function() { 166 | var cacheKey = Backbone.fetchCache.getCacheKey(model, opts); 167 | Backbone.fetchCache.setCache(model, opts, modelResponse); 168 | expect(Backbone.fetchCache._cache[cacheKey].value) 169 | .toEqual(modelResponse); 170 | }); 171 | 172 | it('does not cache if cache: false is passed', function() { 173 | var cacheKey = Backbone.fetchCache.getCacheKey(model, opts); 174 | opts.cache = false; 175 | Backbone.fetchCache.setCache(model, this.opts, modelResponse); 176 | expect(Backbone.fetchCache._cache[cacheKey]).toBeUndefined(); 177 | }); 178 | 179 | }); 180 | 181 | describe('cache expiry', function() { 182 | var cacheKey; 183 | 184 | beforeEach(function() { 185 | this.clock = sinon.useFakeTimers(); 186 | cacheKey = Backbone.fetchCache.getCacheKey(model, this.opts); 187 | }); 188 | 189 | afterEach(function() { 190 | this.clock.restore(); 191 | }); 192 | 193 | it('sets default expiry times for cache keys', function() { 194 | Backbone.fetchCache.setCache(model, { cache: true }, modelResponse); 195 | expect(Backbone.fetchCache._cache[cacheKey].expires) 196 | .toEqual((new Date()).getTime() + (5* 60 * 1000)); 197 | }); 198 | 199 | it('sets expiry times for cache keys', function() { 200 | var opts = { cache: true, expires: 1000 }; 201 | Backbone.fetchCache.setCache(model, opts, modelResponse); 202 | expect(Backbone.fetchCache._cache[cacheKey].expires) 203 | .toEqual((new Date()).getTime() + (opts.expires * 1000)); 204 | }); 205 | 206 | it('is not set if expires: false is set', function() { 207 | var opts = { cache: true, expires: false }; 208 | Backbone.fetchCache.setCache(model, opts, modelResponse); 209 | expect(Backbone.fetchCache._cache[cacheKey].expires) 210 | .toEqual(false); 211 | }); 212 | }); 213 | }); 214 | 215 | describe('.getCache', function() { 216 | var lastSync; 217 | beforeEach(function() { 218 | var opts = {cache: true}; 219 | Backbone.fetchCache.setCache(model, opts, modelResponse); 220 | }); 221 | 222 | it('gets correct cache by string key', function() { 223 | expect(Backbone.fetchCache.getCache(model.url)).toBeDefined(); 224 | expect(Backbone.fetchCache.getCache(model.url).value).toEqual(modelResponse); 225 | }); 226 | 227 | it('gets correct cache by function key', function() { 228 | var key = function () { return model.url; }; 229 | expect(Backbone.fetchCache.getCache(key)).toBeDefined(); 230 | expect(Backbone.fetchCache.getCache(key).value).toEqual(modelResponse); 231 | }); 232 | 233 | it('gets correct cache by entity', function() { 234 | expect(Backbone.fetchCache.getCache(model)).toBeDefined(); 235 | expect(Backbone.fetchCache.getCache(model).value).toEqual(modelResponse); 236 | }); 237 | }); 238 | 239 | describe('.getLastSync', function() { 240 | var lastSync; 241 | beforeEach(function() { 242 | lastSync = (new Date()).getTime(); 243 | var opts = {lastSync: lastSync, cache: true}; 244 | Backbone.fetchCache.setCache(model, opts, modelResponse); 245 | }); 246 | 247 | it('gets correct last sync by string key', function() { 248 | expect(Backbone.fetchCache.getLastSync(model.url)).toEqual(lastSync); 249 | }); 250 | 251 | it('gets correct last sync by function key', function() { 252 | var key = function () { return model.url; }; 253 | expect(Backbone.fetchCache.getLastSync(key)).toEqual(lastSync); 254 | }); 255 | 256 | it('gets correct last sync by entity', function() { 257 | expect(Backbone.fetchCache.getLastSync(model)).toEqual(lastSync); 258 | }); 259 | }); 260 | 261 | describe('.clearItem', function() { 262 | beforeEach(function() { 263 | Backbone.fetchCache._cache = { 264 | '/item/1': { foo: 'bar' }, 265 | '/item/2': { beep: 'boop' }, 266 | '/item/3': { monty: 'zuma' }, 267 | '/item/4?id=007': { james: 'bond' }, 268 | 'foobarbaz': { monkey: 'wrench' } 269 | }; 270 | }); 271 | 272 | it('deletes a single item from the cache', function() { 273 | Backbone.fetchCache.clearItem('/item/1'); 274 | expect(Backbone.fetchCache._cache['/item/1']).toBeUndefined(); 275 | expect(Backbone.fetchCache._cache['/item/2']).toEqual({ beep: 'boop' }); 276 | }); 277 | 278 | it('updates localStorage', function() { 279 | spyOn(Backbone.fetchCache, 'setLocalStorage'); 280 | Backbone.fetchCache.clearItem('/item/1'); 281 | expect(Backbone.fetchCache.setLocalStorage).toHaveBeenCalled(); 282 | }); 283 | 284 | it('takes a function too', function () { 285 | Backbone.fetchCache.clearItem(function () { 286 | return '/item/3'; 287 | }); 288 | expect(Backbone.fetchCache._cache['/item/3']).toBeUndefined(); 289 | }); 290 | 291 | it('or entity with url', function () { 292 | var entity = { 293 | url: function () { 294 | return '/item/4'; 295 | } 296 | }; 297 | Backbone.fetchCache.clearItem(entity, {data: {id: '007'}}); 298 | expect(Backbone.fetchCache._cache['/item/4?id=007']).toBeUndefined(); 299 | }); 300 | 301 | it('or entity with custom key', function () { 302 | var entity = { 303 | getCacheKey: function () { 304 | return 'foobarbaz'; 305 | } 306 | }; 307 | Backbone.fetchCache.clearItem(entity); 308 | expect(Backbone.fetchCache._cache['foobarbaz']).toBeUndefined(); 309 | }); 310 | }); 311 | 312 | describe('.setLocalStorage', function() { 313 | it('puts the cache into localStorage', function() { 314 | var cache = Backbone.fetchCache._cache = { 315 | '/url1': { expires: false, value: { bacon: 'sandwich' } }, 316 | '/url2': { expires: false, value: { egg: 'roll' } } 317 | }; 318 | Backbone.fetchCache.setLocalStorage(); 319 | expect(localStorage.getItem('backboneCache')).toEqual(JSON.stringify(cache)); 320 | }); 321 | 322 | it('does not put the cache into localStorage if localStorage is false', function() { 323 | var cache = Backbone.fetchCache._cache = { 324 | '/url1': { expires: false, value: { bacon: 'sandwich' } }, 325 | '/url2': { expires: false, value: { egg: 'roll' } } 326 | }; 327 | Backbone.fetchCache.localStorage = false; 328 | Backbone.fetchCache.setLocalStorage(); 329 | 330 | expect(localStorage.getItem('backboneCache')).toEqual(); 331 | 332 | Backbone.fetchCache.localStorage = true; // restore 333 | }); 334 | }); 335 | 336 | describe('.getLocalStorage', function() { 337 | it('primes the cache from localStorage', function() { 338 | var cache = { 339 | '/url1': { expires: false, value: { bacon: 'sandwich' } }, 340 | '/url2': { expires: false, value: { egg: 'roll' } } 341 | }; 342 | localStorage.setItem('backboneCache', JSON.stringify(cache)); 343 | Backbone.fetchCache.getLocalStorage(); 344 | expect(Backbone.fetchCache._cache).toEqual(cache); 345 | }); 346 | 347 | it('always primes the cache with an object', function() { 348 | Backbone.fetchCache.getLocalStorage(); 349 | expect(Backbone.fetchCache._cache).toEqual({}); 350 | }); 351 | }); 352 | 353 | describe('Automatic expiry when quota is met', function() { 354 | describe('.prioritize', function() { 355 | it('prioritizes older results by default', function() { 356 | var cache = { 357 | '/url1': { expires: 1000, value: { bacon: 'sandwich' } }, 358 | '/url2': { expires: 1500, value: { egg: 'roll' } } 359 | }; 360 | localStorage.setItem('backboneCache', JSON.stringify(cache)); 361 | Backbone.fetchCache.getLocalStorage(); 362 | expect(Backbone.fetchCache._prioritize()).toBeDefined(); 363 | expect(Backbone.fetchCache._prioritize()).toEqual('/url1'); 364 | }); 365 | }); 366 | 367 | describe('.priorityFn', function() { 368 | it('should take a custom priorityFn sorting function', function() { 369 | var cache = { 370 | '/url1': { expires: 1000, value: { bacon: 'sandwich' } }, 371 | '/url2': { expires: 1500, value: { egg: 'roll' } } 372 | }; 373 | localStorage.setItem('backboneCache', JSON.stringify(cache)); 374 | Backbone.fetchCache.getLocalStorage(); 375 | Backbone.fetchCache.priorityFn = function(a, b) { 376 | return b.expires - a.expires; 377 | }; 378 | expect(Backbone.fetchCache._prioritize()).toEqual('/url2'); 379 | }); 380 | }); 381 | 382 | describe('.deleteCacheWithPriority', function() { 383 | it('calls deleteCacheWithPriority if a QUOTA_EXCEEDED_ERR is thrown', function() { 384 | function QuotaError(message) { 385 | this.code = 22; 386 | } 387 | 388 | QuotaError.prototype = new Error(); 389 | 390 | spyOn(localStorage, 'setItem').andThrow(new QuotaError()); 391 | 392 | spyOn(Backbone.fetchCache, '_deleteCacheWithPriority'); 393 | 394 | Backbone.fetchCache._cache = { 395 | '/url1': { expires: 1000, value: { bacon: 'sandwich' } }, 396 | '/url2': { expires: 1500, value: { egg: 'roll' } } 397 | }; 398 | Backbone.fetchCache.setLocalStorage(); 399 | expect(Backbone.fetchCache._deleteCacheWithPriority).toHaveBeenCalled(); 400 | }); 401 | 402 | it('calls deleteCacheWithPriority if a QUOTA_EXCEEDED_ERR is thrown in IE', function() { 403 | function IEQuotaError(message) { 404 | this.number = 22; 405 | } 406 | 407 | IEQuotaError.prototype = new Error(); 408 | 409 | spyOn(localStorage, 'setItem').andThrow(new IEQuotaError()); 410 | 411 | spyOn(Backbone.fetchCache, '_deleteCacheWithPriority'); 412 | 413 | Backbone.fetchCache._cache = { 414 | '/url1': { expires: 1000, value: { bacon: 'sandwich' } }, 415 | '/url2': { expires: 1500, value: { egg: 'roll' } } 416 | }; 417 | Backbone.fetchCache.setLocalStorage(); 418 | expect(Backbone.fetchCache._deleteCacheWithPriority).toHaveBeenCalled(); 419 | }); 420 | 421 | it('calls deleteCacheWithPriority if a QUOTA_EXCEEDED_ERR is thrown in Firefox', function() { 422 | function FFQuotaError(message) { 423 | this.code = 1014; 424 | } 425 | 426 | FFQuotaError.prototype = new Error(); 427 | 428 | spyOn(localStorage, 'setItem').andThrow(new FFQuotaError()); 429 | 430 | spyOn(Backbone.fetchCache, '_deleteCacheWithPriority'); 431 | 432 | Backbone.fetchCache._cache = { 433 | '/url1': { expires: 1000, value: { bacon: 'sandwich' } }, 434 | '/url2': { expires: 1500, value: { egg: 'roll' } } 435 | }; 436 | Backbone.fetchCache.setLocalStorage(); 437 | expect(Backbone.fetchCache._deleteCacheWithPriority).toHaveBeenCalled(); 438 | }); 439 | 440 | it('should delete a cached item according to what is returned by priorityFn', function() { 441 | var cache = { 442 | '/url1': { expires: 1000, value: { bacon: 'sandwich' } }, 443 | '/url2': { expires: 1500, value: { egg: 'roll' } } 444 | }; 445 | localStorage.setItem('backboneCache', JSON.stringify(cache)); 446 | Backbone.fetchCache.getLocalStorage(); 447 | Backbone.fetchCache._deleteCacheWithPriority(); 448 | expect(Backbone.fetchCache._cache) 449 | .toEqual({'/url2': { expires: 1500, value: { egg: 'roll' } }}); 450 | }); 451 | }); 452 | }); 453 | 454 | describe('Backbone.Model', function() { 455 | describe('#fetch', function() { 456 | var cacheData; 457 | 458 | beforeEach(function() { 459 | cacheData = { cheese: 'pickle' }; 460 | }); 461 | 462 | it('saves returned attributes to the cache', function() { 463 | var cacheKey = Backbone.fetchCache.getCacheKey(model); 464 | model.fetch({ cache: true }); 465 | server.respond(); 466 | expect(Backbone.fetchCache._cache[cacheKey].value) 467 | .toEqual(model.toJSON()); 468 | }); 469 | 470 | it('passes the instance and options through to setCache', function() { 471 | var opts = { banana: 'bread' }; 472 | spyOn(Backbone.fetchCache, 'setCache'); 473 | 474 | model.fetch(opts); 475 | server.respond(); 476 | 477 | expect(Backbone.fetchCache.setCache.calls[0].args[0]).toEqual(model); 478 | expect(Backbone.fetchCache.setCache.calls[0].args[1]).toEqual(opts); 479 | }); 480 | 481 | it('sets data from the cache if cache: true is set', function() { 482 | Backbone.fetchCache._cache[model.url] = { 483 | value: cacheData, 484 | expires: (new Date()).getTime() + (5* 60 * 1000) 485 | }; 486 | 487 | waitsFor(promiseComplete(model.fetch({ cache: true }))); 488 | 489 | runs(function() { 490 | expect(model.toJSON()).toEqual(cacheData); 491 | }); 492 | }); 493 | 494 | it('does not set cache data if cache: true is not set', function() { 495 | Backbone.fetchCache._cache[model.url] = { 496 | value: cacheData, 497 | expires: (new Date()).getTime() + (5* 60 * 1000) 498 | }; 499 | 500 | waitsFor(promiseComplete(model.fetch())); 501 | server.respond(); 502 | 503 | runs(function() { 504 | expect(model.toJSON()).not.toEqual(cacheData); 505 | expect(model.toJSON()).toEqual(modelResponse); 506 | }); 507 | }); 508 | 509 | it('does not set cache data if the cache item is stale', function() { 510 | Backbone.fetchCache._cache[model.url] = { 511 | value: cacheData, 512 | expires: (new Date()).getTime() - (5* 60 * 1000) 513 | }; 514 | 515 | waitsFor(promiseComplete(model.fetch())); 516 | 517 | server.respond(); 518 | 519 | runs(function() { 520 | expect(model.toJSON()).not.toEqual(cacheData); 521 | expect(model.toJSON()).toEqual(modelResponse); 522 | }); 523 | }); 524 | 525 | it('sets cache data if the item has expires: false', function() { 526 | var cacheData = { cheese: 'pickle' }; 527 | Backbone.fetchCache._cache[model.url] = { 528 | value: cacheData, 529 | expires: false 530 | }; 531 | 532 | waitsFor(promiseComplete(model.fetch({ cache: true }))); 533 | 534 | runs(function() { 535 | expect(model.toJSON()).toEqual(cacheData); 536 | }); 537 | }); 538 | 539 | it('returns an unfulfilled promise', function() { 540 | var promise = model.fetch(); 541 | expect(promise).toBeAPromise(); 542 | expect(promise).toBeUnresolved(); 543 | }); 544 | 545 | describe('on AJAX error', function() { 546 | 547 | it('rejects the promise', function() { 548 | var promise = errorModel.fetch(); 549 | 550 | waitsFor(promiseComplete(promise)); 551 | server.respond(); 552 | 553 | runs(function() { 554 | expect(Backbone.fetchCache._cache[errorModel.url]).toBeUndefined(); 555 | expect(promise.state()).toBe('rejected'); 556 | }); 557 | }); 558 | 559 | it('calls the error callback', function() { 560 | var spy = jasmine.createSpy('error'); 561 | var promise = errorModel.fetch({ error: spy }); 562 | 563 | waitsFor(promiseComplete(promise)); 564 | server.respond(); 565 | 566 | runs(function() { 567 | expect(Backbone.fetchCache._cache[errorModel.url]).toBeUndefined(); 568 | expect(spy).toHaveBeenCalled(); 569 | }); 570 | }); 571 | }); 572 | 573 | describe('on a cache hit', function() { 574 | var promise, successSpy, cacheData; 575 | 576 | beforeEach(function() { 577 | cacheData = { cheese: 'pickle' }; 578 | successSpy = jasmine.createSpy('fetch success'); 579 | 580 | Backbone.fetchCache._cache[model.url] = { 581 | value: cacheData, 582 | expires: (new Date()).getTime() + (5* 60 * 1000), 583 | success: successSpy 584 | }; 585 | promise = model.fetch({ cache: true }); 586 | }); 587 | 588 | it('returns an unfulfilled promise', function() { 589 | expect(promise).toBeAPromise(); 590 | expect(promise).toBeUnresolved(); 591 | }); 592 | 593 | it('fulfills the promise asynchronously', function() { 594 | waitsFor(promiseComplete(promise)); 595 | runs(function() { 596 | expect(promise).toBeResolved(); 597 | }); 598 | }); 599 | 600 | it('resolves the promise with the model instance', function() { 601 | promise.done(successSpy); 602 | waitsFor(promiseComplete(promise)); 603 | runs(function() { 604 | expect(successSpy).toHaveBeenCalledWith(model); 605 | }); 606 | }); 607 | 608 | it('calls the success callback with the model instance, response data and fetch options', function() { 609 | var options = { 610 | cache: true, 611 | success: successSpy 612 | }; 613 | 614 | waitsFor(promiseComplete(model.fetch(options))); 615 | 616 | runs(function() { 617 | expect(successSpy).toHaveBeenCalledWith(model, cacheData, options); 618 | }); 619 | }); 620 | }); 621 | 622 | describe('with prefill: true option', function() { 623 | var cacheData; 624 | 625 | beforeEach(function(){ 626 | cacheData = { cheese: 'pickle' }; 627 | Backbone.fetchCache._cache[model.url] = { 628 | value: cacheData, 629 | expires: (new Date()).getTime() + (5* 60 * 1000) 630 | }; 631 | }); 632 | 633 | it('sets cache data and then makes an xhr request', function() { 634 | waitsFor(promiseNotified(model.fetch({ prefill: true }))); 635 | 636 | runs(function() { 637 | expect(model.toJSON()).toEqual(cacheData); 638 | 639 | server.respond(); 640 | 641 | for (var key in modelResponse) { 642 | if (modelResponse.hasOwnProperty(key)) { 643 | expect(model.toJSON()[key]).toEqual(modelResponse[key]); 644 | } 645 | } 646 | }); 647 | }); 648 | 649 | it('calls the prefillSuccess and success callbacks in order', function() { 650 | var prefillSuccess = jasmine.createSpy('prefillSuccess'), 651 | success = jasmine.createSpy('success'); 652 | 653 | var promise = model.fetch({ 654 | prefill: true, 655 | success: success, 656 | prefillSuccess: prefillSuccess 657 | }); 658 | 659 | waitsFor(promiseNotified(promise)); 660 | 661 | runs(function() { 662 | expect(prefillSuccess.calls[0].args[0]).toEqual(model); 663 | expect(prefillSuccess.calls[0].args[1]).toEqual(model.attributes); 664 | expect(success).not.toHaveBeenCalled(); 665 | 666 | server.respond(); 667 | 668 | expect(success.calls[0].args[0]).toEqual(model); 669 | expect(success.calls[0].args[1]).toEqual(modelResponse); 670 | }); 671 | }); 672 | 673 | it('triggers sync on prefill success and success', function() { 674 | var prefillSuccess = jasmine.createSpy('prefillSuccess'), 675 | success = jasmine.createSpy('success'), 676 | sync = jasmine.createSpy('sync'), 677 | cachesync = jasmine.createSpy('cachesync'); 678 | 679 | model.bind('sync', sync); 680 | model.bind('cachesync', cachesync); 681 | 682 | var promise = model.fetch({ 683 | prefill: true, 684 | success: success, 685 | prefillSuccess: prefillSuccess 686 | }); 687 | 688 | waitsFor(promiseNotified(promise)); 689 | 690 | runs(function() { 691 | expect(sync).toHaveBeenCalled(); 692 | expect(sync.callCount).toEqual(1); 693 | 694 | expect(cachesync).toHaveBeenCalled(); 695 | expect(cachesync.callCount).toEqual(1); 696 | 697 | server.respond(); 698 | 699 | // Ensure cachesync was not called on this second go around 700 | expect(cachesync.callCount).toEqual(1); 701 | 702 | expect(sync).toHaveBeenCalled(); 703 | expect(sync.callCount).toEqual(2); 704 | 705 | expect(success.calls[0].args[0]).toEqual(model); 706 | expect(success.calls[0].args[1]).toEqual(modelResponse); 707 | }); 708 | }); 709 | 710 | it('triggers progress on the promise on cache hit', function() { 711 | var progress = jasmine.createSpy('progress'); 712 | var promise = model.fetch({ prefill: true }).progress(progress); 713 | 714 | waitsFor(promiseNotified(promise)); 715 | 716 | runs(function() { 717 | expect(progress).toHaveBeenCalledWith(model); 718 | }); 719 | }); 720 | 721 | it('fulfills the promise on AJAX success', function() { 722 | var success = jasmine.createSpy('success'); 723 | model.fetch({ prefill: true }).done(success); 724 | 725 | server.respond(); 726 | 727 | expect(success.calls[0].args[0]).toEqual(model); 728 | expect(success.calls[0].args[1]).toEqual(modelResponse); 729 | }); 730 | }); 731 | 732 | describe('with prefillExpires: 1000 option', function() { 733 | var cacheData; 734 | 735 | beforeEach(function() { 736 | cacheData = { cheese: 'pickle' }; 737 | }); 738 | 739 | it('returns value if cached value is neither expired nor prefill expired', function() { 740 | Backbone.fetchCache._cache[model.url] = { 741 | value: cacheData, 742 | expires: (new Date()).getTime() + (5 * 60 * 1000), 743 | prefillExpires: (new Date()).getTime() + (5 * 60 * 1000) 744 | }; 745 | 746 | var promise = model.fetch({ 747 | prefill: true, 748 | prefillExpires: 1000 749 | }); 750 | 751 | waitsFor(promiseComplete(promise)); 752 | 753 | runs(function() { 754 | expect(model.toJSON()).toEqual(cacheData); 755 | }); 756 | }); 757 | 758 | it('fetches value if cached value is valid but prefill expired', function() { 759 | Backbone.fetchCache._cache[model.url] = { 760 | value: cacheData, 761 | expires: (new Date()).getTime() + (5 * 60 * 1000), 762 | prefillExpires: (new Date()).getTime() - (5 * 60 * 1000) 763 | }; 764 | 765 | var promise = model.fetch({ 766 | prefill: true, 767 | prefillExpires: 1000 768 | }); 769 | 770 | waitsFor(promiseComplete(promise)); 771 | server.respond(); 772 | 773 | runs(function() { 774 | expect(model.toJSON()).toEqual(modelResponse); 775 | }); 776 | }); 777 | 778 | it('triggers progress if cached value is valid but prefill expired', function() { 779 | Backbone.fetchCache._cache[model.url] = { 780 | value: cacheData, 781 | expires: (new Date()).getTime() + (5 * 60 * 1000), 782 | prefillExpires: (new Date()).getTime() - (5 * 60 * 1000) 783 | }; 784 | var progress = jasmine.createSpy('progress'); 785 | 786 | var promise = model.fetch({ 787 | prefill: true, 788 | prefillExpires: 1000 789 | }).progress(progress); 790 | 791 | waitsFor(promiseNotified(promise)); 792 | 793 | runs(function() { 794 | expect(progress).toHaveBeenCalledWith(model); 795 | }); 796 | }); 797 | 798 | it("fetches value if value isn't cached", function() { 799 | Backbone.fetchCache._cache = {}; 800 | 801 | var promise = model.fetch({ 802 | prefill: true, 803 | prefillExpires: 1000 804 | }); 805 | 806 | waitsFor(promiseComplete(promise)); 807 | server.respond(); 808 | 809 | runs(function() { 810 | expect(model.toJSON()).toEqual(modelResponse); 811 | }); 812 | }); 813 | 814 | it('fetches value if cached value is expired', function() { 815 | Backbone.fetchCache._cache[model.url] = { 816 | value: cacheData, 817 | expires: (new Date()).getTime() - (5 * 60 * 1000), 818 | prefillExpires: (new Date()).getTime() - (5 * 60 * 1000) 819 | }; 820 | 821 | var promise = model.fetch({ 822 | prefill: true, 823 | prefillExpires: 1000 824 | }); 825 | 826 | waitsFor(promiseComplete(promise)); 827 | server.respond(); 828 | 829 | runs(function() { 830 | expect(model.toJSON()).not.toEqual(cacheData); 831 | expect(model.toJSON()).toEqual(modelResponse); 832 | }); 833 | }); 834 | 835 | it("sets the prefillExpires value if cached value doesn't exist", function() { 836 | Backbone.fetchCache._cache = {}; 837 | 838 | var promise = model.fetch({ 839 | prefill: true, 840 | prefillExpires: 1000 841 | }); 842 | 843 | waitsFor(promiseComplete(promise)); 844 | server.respond(); 845 | 846 | runs(function() { 847 | expect(Backbone.fetchCache._cache[model.url].prefillExpires / 100).toBeCloseTo(((new Date()).getTime() + 1000000) / 100, 0); 848 | }); 849 | }); 850 | }); 851 | 852 | describe('with async: false option', function() { 853 | it('resolves synchronously', function() { 854 | Backbone.fetchCache._cache[model.url] = { 855 | value: cacheData, 856 | expires: (new Date()).getTime() + (5* 60 * 1000) 857 | }; 858 | 859 | model.fetch({ cache: true, async: false }); 860 | expect(model.toJSON()).toEqual(cacheData); 861 | }); 862 | }); 863 | 864 | describe('with caching disabled', function(){ 865 | beforeEach(function(){ 866 | Backbone.fetchCache.enabled = false; 867 | }); 868 | 869 | afterEach(function(){ 870 | Backbone.fetchCache.enabled = true; 871 | }); 872 | 873 | it("doesn't set cache", function(){ 874 | var cacheKey = Backbone.fetchCache.getCacheKey(model); 875 | model.fetch({ cache: true }); 876 | server.respond(); 877 | expect(Backbone.fetchCache._cache[cacheKey]) 878 | .toBeUndefined(); 879 | }); 880 | 881 | it("doesn't use cache", function(){ 882 | Backbone.fetchCache._cache[model.url] = { 883 | value: cacheData, 884 | expires: (new Date()).getTime() + (5* 60 * 1000) 885 | }; 886 | 887 | waitsFor(promiseComplete(model.fetch({cache: true}))); 888 | server.respond(); 889 | 890 | runs(function() { 891 | expect(model.toJSON()).not.toEqual(cacheData); 892 | expect(model.toJSON()).toEqual(modelResponse); 893 | }); 894 | }); 895 | }); 896 | 897 | describe('with context option', function() { 898 | var context; 899 | 900 | function setFoo() { 901 | this.foo = 'bar'; 902 | } 903 | 904 | beforeEach(function() { 905 | context = {}; 906 | }); 907 | 908 | describe('on AJAX success', function() { 909 | it('resolves the promise with context', function() { 910 | var done = jasmine.createSpy('done').andCallFake(setFoo); 911 | var promise = model.fetch({ 912 | context: context 913 | }); 914 | 915 | promise.done(done); 916 | waitsFor(promiseComplete(promise)); 917 | server.respond(); 918 | 919 | runs(function() { 920 | expect(done).toHaveBeenCalled(); 921 | expect(context.foo).toBe('bar'); 922 | }); 923 | }); 924 | }); 925 | 926 | describe('on AJAX error', function() { 927 | it('rejects the promise with context', function() { 928 | var fail = jasmine.createSpy('fail').andCallFake(setFoo); 929 | var promise = errorModel.fetch({ 930 | context: context 931 | }); 932 | 933 | promise.fail(fail); 934 | waitsFor(promiseComplete(promise)); 935 | server.respond(); 936 | 937 | runs(function() { 938 | expect(fail).toHaveBeenCalled(); 939 | expect(context.foo).toBe('bar'); 940 | }); 941 | }); 942 | }); 943 | 944 | describe('on a cache hit', function() { 945 | var cacheData; 946 | 947 | beforeEach(function() { 948 | cacheData = { cheese: 'pickle' }; 949 | Backbone.fetchCache._cache[model.url] = { 950 | value: cacheData, 951 | expires: (new Date()).getTime() + (5* 60 * 1000) 952 | }; 953 | }); 954 | 955 | it('resolves the promise with context', function() { 956 | var done = jasmine.createSpy('done').andCallFake(setFoo); 957 | var promise = model.fetch({ 958 | cache: true, 959 | context: context 960 | }); 961 | 962 | promise.done(done); 963 | waitsFor(promiseComplete(promise)); 964 | server.respond(); 965 | 966 | runs(function() { 967 | expect(done).toHaveBeenCalled(); 968 | expect(context.foo).toBe('bar'); 969 | }); 970 | }); 971 | 972 | it('calls the prefillSuccess callback with context', function() { 973 | var prefillSuccess = jasmine.createSpy('prefillSuccess').andCallFake(setFoo); 974 | var promise = model.fetch({ 975 | context: context, 976 | prefill: true, 977 | prefillSuccess: prefillSuccess 978 | }); 979 | 980 | waitsFor(promiseNotified(promise)); 981 | 982 | runs(function() { 983 | expect(prefillSuccess).toHaveBeenCalled(); 984 | expect(context.foo).toBe('bar'); 985 | }); 986 | }); 987 | 988 | it('triggers progress on the promise with context', function() { 989 | var progress = jasmine.createSpy('progress').andCallFake(setFoo); 990 | var promise = model.fetch({ 991 | context: context, 992 | prefill: true 993 | }); 994 | 995 | promise.progress(progress); 996 | waitsFor(promiseNotified(promise)); 997 | 998 | runs(function() { 999 | expect(progress).toHaveBeenCalled(); 1000 | expect(context.foo).toBe('bar'); 1001 | }); 1002 | }); 1003 | 1004 | it('calls the success callback with context', function() { 1005 | var success = jasmine.createSpy('success').andCallFake(setFoo); 1006 | var promise = model.fetch({ 1007 | cache: true, 1008 | context: context, 1009 | success: success 1010 | }); 1011 | 1012 | waitsFor(promiseComplete(promise)); 1013 | server.respond(); 1014 | 1015 | runs(function() { 1016 | expect(success).toHaveBeenCalled(); 1017 | expect(context.foo).toBe('bar'); 1018 | }); 1019 | }); 1020 | }); 1021 | }); 1022 | }); 1023 | 1024 | describe('#sync', function() { 1025 | describe('using model instance url', function () { 1026 | var cacheData; 1027 | 1028 | beforeEach(function() { 1029 | var cache = {}; 1030 | cacheData = { some: 'data' }; 1031 | cache[model.url] = cacheData; 1032 | localStorage.setItem('backboneCache', JSON.stringify(cache)); 1033 | Backbone.fetchCache.getLocalStorage(); 1034 | }); 1035 | 1036 | it('clears the cache for the model on create', function() { 1037 | model.sync('create', model, {}); 1038 | expect(Backbone.fetchCache._cache[model.url]).toBeUndefined(); 1039 | }); 1040 | 1041 | it('clears the cache for the model on update', function() { 1042 | model.sync('update', model, {}); 1043 | expect(Backbone.fetchCache._cache[model.url]).toBeUndefined(); 1044 | }); 1045 | 1046 | it('clears the cache for the model on patch', function() { 1047 | model.sync('create', model, {}); 1048 | expect(Backbone.fetchCache._cache[model.url]).toBeUndefined(); 1049 | }); 1050 | 1051 | it('clears the cache for the model on delete', function() { 1052 | model.sync('create', model, {}); 1053 | expect(Backbone.fetchCache._cache[model.url]).toBeUndefined(); 1054 | }); 1055 | 1056 | it('does not clear the cache for the model on read', function() { 1057 | model.sync('read', model, {}); 1058 | expect(Backbone.fetchCache._cache[model.url]).toEqual(cacheData); 1059 | }); 1060 | }); 1061 | describe('using options-given url', function() { 1062 | var cacheData; 1063 | var optionsGiven; 1064 | 1065 | beforeEach(function() { 1066 | optionsGiven = { 'url' : '/given-url' }; 1067 | var cache = {}; 1068 | cacheData = { some: 'data' }; 1069 | cache[optionsGiven.url] = cacheData; 1070 | localStorage.setItem('backboneCache', JSON.stringify(cache)); 1071 | Backbone.fetchCache.getLocalStorage(); 1072 | }); 1073 | 1074 | it('clears the cache for the model on create', function() { 1075 | model.sync('create', model, optionsGiven); 1076 | expect(Backbone.fetchCache._cache[optionsGiven.url]).toBeUndefined(); 1077 | }); 1078 | 1079 | it('clears the cache for the model on update', function() { 1080 | model.sync('update', model, optionsGiven); 1081 | expect(Backbone.fetchCache._cache[optionsGiven.url]).toBeUndefined(); 1082 | }); 1083 | 1084 | it('clears the cache for the model on patch', function() { 1085 | model.sync('create', model, optionsGiven); 1086 | expect(Backbone.fetchCache._cache[optionsGiven.url]).toBeUndefined(); 1087 | }); 1088 | 1089 | it('clears the cache for the model on delete', function() { 1090 | model.sync('create', model, optionsGiven); 1091 | expect(Backbone.fetchCache._cache[optionsGiven.url]).toBeUndefined(); 1092 | }); 1093 | 1094 | it('does not clear the cache for the model on read', function() { 1095 | model.sync('read', model, optionsGiven); 1096 | expect(Backbone.fetchCache._cache[optionsGiven.url]).toEqual(cacheData); 1097 | }); 1098 | }); 1099 | 1100 | it('calls super', function() { 1101 | spyOn(Backbone.fetchCache._superMethods, 'modelSync'); 1102 | model.sync('create', model, {}); 1103 | expect(Backbone.fetchCache._superMethods.modelSync).toHaveBeenCalled(); 1104 | }); 1105 | 1106 | it('returns the result of calling super', function() { 1107 | expect(model.sync('create', model, {})).toBeAPromise(); 1108 | }); 1109 | 1110 | describe('with an associated collection', function() { 1111 | beforeEach(function() { 1112 | var cache = {}; 1113 | model.collection = collection; 1114 | cache[Backbone.fetchCache.getCacheKey(collection)] = [{ some: 'data' }]; 1115 | localStorage.setItem('backboneCache', JSON.stringify(cache)); 1116 | Backbone.fetchCache.getLocalStorage(); 1117 | }); 1118 | 1119 | it('clears the cache for the collection', function() { 1120 | var cacheKey = Backbone.fetchCache.getCacheKey(collection); 1121 | model.sync('create', model, {}); 1122 | expect(Backbone.fetchCache._cache[cacheKey]).toBeUndefined(); 1123 | }); 1124 | }); 1125 | }); 1126 | }); 1127 | 1128 | describe('Backbone.Collection', function() { 1129 | describe('#fetch', function() { 1130 | var cacheData; 1131 | 1132 | beforeEach(function() { 1133 | cacheData = [{ cheese: 'pickle' }, { salt: 'vinegar' }]; 1134 | }); 1135 | 1136 | it('returns an unfulfilled promise', function() { 1137 | var promise = collection.fetch(); 1138 | expect(promise).toBeAPromise(); 1139 | expect(promise).toBeUnresolved(); 1140 | }); 1141 | 1142 | it('saves returned attributes to the cache', function() { 1143 | collection.fetch({ cache: true }); 1144 | server.respond(); 1145 | expect(Backbone.fetchCache._cache[collection.url].value) 1146 | .toEqual(collection.toJSON()); 1147 | }); 1148 | 1149 | it('passes the instance and options through to setCache', function() { 1150 | var opts = { banana: 'bread' }; 1151 | spyOn(Backbone.fetchCache, 'setCache'); 1152 | 1153 | collection.fetch(opts); 1154 | server.respond(); 1155 | 1156 | expect(Backbone.fetchCache.setCache.calls[0].args[0]).toEqual(collection); 1157 | expect(Backbone.fetchCache.setCache.calls[0].args[1]).toEqual(opts); 1158 | }); 1159 | 1160 | it('sets data cache data if cache: true is set', function() { 1161 | Backbone.fetchCache._cache[collection.url] = { 1162 | value: cacheData, 1163 | expires: (new Date()).getTime() + (5* 60 * 1000) 1164 | }; 1165 | 1166 | waitsFor(promiseComplete(collection.fetch({ 1167 | cache: true 1168 | }))); 1169 | 1170 | runs(function() { 1171 | expect(collection.toJSON()).toEqual(cacheData); 1172 | }); 1173 | }); 1174 | 1175 | it('does not set cache data if cache: true is not set', function() { 1176 | Backbone.fetchCache._cache[collection.url] = { 1177 | value: cacheData, 1178 | expires: (new Date()).getTime() + (5* 60 * 1000) 1179 | }; 1180 | 1181 | collection.fetch(); 1182 | server.respond(); 1183 | 1184 | expect(collection.toJSON()).not.toEqual(cacheData); 1185 | expect(collection.toJSON()).toEqual(collectionResponse); 1186 | }); 1187 | 1188 | it('does not set cache data if the cache item is stale', function() { 1189 | Backbone.fetchCache._cache[collection.url] = { 1190 | value: cacheData, 1191 | expires: (new Date()).getTime() - (5* 60 * 1000) 1192 | }; 1193 | 1194 | collection.fetch(); 1195 | server.respond(); 1196 | 1197 | expect(collection.toJSON()).not.toEqual(cacheData); 1198 | expect(collection.toJSON()).toEqual(collectionResponse); 1199 | }); 1200 | 1201 | it('sets cache data if the item has expires: false', function() { 1202 | Backbone.fetchCache._cache[collection.url] = { 1203 | value: cacheData, 1204 | expires: false 1205 | }; 1206 | 1207 | waitsFor(promiseComplete(collection.fetch({ 1208 | cache: true 1209 | }))); 1210 | 1211 | runs(function() { 1212 | expect(collection.toJSON()).toEqual(cacheData); 1213 | }); 1214 | }); 1215 | 1216 | describe('on AJAX error', function() { 1217 | 1218 | it('rejects the promise', function() { 1219 | var promise = errorCollection.fetch(); 1220 | 1221 | waitsFor(promiseComplete(promise)); 1222 | server.respond(); 1223 | 1224 | runs(function() { 1225 | expect(Backbone.fetchCache._cache[errorCollection.url]).toBeUndefined(); 1226 | expect(promise.state()).toBe('rejected'); 1227 | }); 1228 | }); 1229 | 1230 | it('calls the error callback', function() { 1231 | var spy = jasmine.createSpy('error'); 1232 | var promise = errorCollection.fetch({ error: spy }); 1233 | 1234 | waitsFor(promiseComplete(promise)); 1235 | server.respond(); 1236 | 1237 | runs(function() { 1238 | expect(Backbone.fetchCache._cache[errorCollection.url]).toBeUndefined(); 1239 | expect(spy).toHaveBeenCalled(); 1240 | }); 1241 | }); 1242 | }); 1243 | 1244 | describe('on cache hit', function() { 1245 | beforeEach(function() { 1246 | Backbone.fetchCache._cache[collection.url] = { 1247 | value: cacheData, 1248 | expires: (new Date()).getTime() + (5* 60 * 1000) 1249 | }; 1250 | }); 1251 | 1252 | it('returns an unfulfilled promise', function() { 1253 | var promise = collection.fetch({ cache: true }); 1254 | 1255 | expect(promise).toBeAPromise(); 1256 | expect(promise).toBeUnresolved(); 1257 | }); 1258 | 1259 | it('calls set according to options', function() { 1260 | var options = { cache: true, remove: false }; 1261 | 1262 | spyOn(collection, 'set'); 1263 | waitsFor(promiseComplete(collection.fetch(options))); 1264 | 1265 | runs(function() { 1266 | expect(collection.set).toHaveBeenCalledWith(cacheData, options); 1267 | }); 1268 | }); 1269 | 1270 | it('calls reset according to options', function() { 1271 | var options = { cache: true, reset: true }; 1272 | 1273 | spyOn(collection, 'reset'); 1274 | waitsFor(promiseComplete(collection.fetch(options))); 1275 | 1276 | runs(function() { 1277 | expect(collection.reset).toHaveBeenCalledWith(cacheData, options); 1278 | }); 1279 | }); 1280 | 1281 | it('fulfills the promise with the collection instance', function() { 1282 | var spy = jasmine.createSpy('success'); 1283 | var promise = collection.fetch({ cache: true }).done(spy); 1284 | 1285 | waitsFor(promiseComplete(promise)); 1286 | runs(function() { 1287 | expect(spy).toHaveBeenCalledWith(collection); 1288 | }); 1289 | }); 1290 | 1291 | it('calls success callback with the collection instance, response data and fetch options', function() { 1292 | var success = jasmine.createSpy('success'); 1293 | var options = { 1294 | cache: true, 1295 | success: success 1296 | }; 1297 | 1298 | waitsFor(promiseComplete(collection.fetch(options))); 1299 | runs(function() { 1300 | expect(success).toHaveBeenCalledWith(collection, cacheData, options); 1301 | }); 1302 | }); 1303 | }); 1304 | 1305 | describe('with prefill: true option', function() { 1306 | beforeEach(function(){ 1307 | Backbone.fetchCache._cache[collection.url] = { 1308 | value: cacheData, 1309 | expires: (new Date()).getTime() + (5* 60 * 1000) 1310 | }; 1311 | }); 1312 | 1313 | it('sets cache data and makes an xhr request', function() { 1314 | waitsFor(promiseNotified(collection.fetch({ prefill: true }))); 1315 | 1316 | runs(function() { 1317 | expect(collection.toJSON()).toEqual(cacheData); 1318 | 1319 | server.respond(); 1320 | 1321 | expect(collection.toJSON()).toEqual(collectionResponse); 1322 | }); 1323 | }); 1324 | 1325 | it('calls the prefillSuccess and success callbacks in order', function() { 1326 | var prefillSuccess = jasmine.createSpy('prefillSuccess'), 1327 | success = jasmine.createSpy('success'); 1328 | 1329 | waitsFor(promiseNotified(collection.fetch({ 1330 | prefill: true, 1331 | success: success, 1332 | prefillSuccess: prefillSuccess 1333 | }))); 1334 | 1335 | runs(function() { 1336 | expect(prefillSuccess.calls[0].args[0]).toEqual(collection); 1337 | expect(prefillSuccess.calls[0].args[1]).toEqual(collection.attributes); 1338 | expect(success).not.toHaveBeenCalled(); 1339 | 1340 | server.respond(); 1341 | expect(success.calls[0].args[0]).toEqual(collection); 1342 | expect(success.calls[0].args[1]).toEqual(collectionResponse); 1343 | }); 1344 | }); 1345 | 1346 | it('triggers sync on prefill success and success', function() { 1347 | var prefillSuccess = jasmine.createSpy('prefillSuccess'), 1348 | success = jasmine.createSpy('success'), 1349 | sync = jasmine.createSpy('sync'), 1350 | cachesync = jasmine.createSpy('cachesync'); 1351 | 1352 | collection.bind('sync', sync); 1353 | collection.bind('cachesync', cachesync); 1354 | 1355 | waitsFor(promiseNotified(collection.fetch({ 1356 | prefill: true, 1357 | success: success, 1358 | prefillSuccess: prefillSuccess 1359 | }))); 1360 | 1361 | runs(function() { 1362 | expect(sync).toHaveBeenCalled(); 1363 | expect(sync.callCount).toEqual(1); 1364 | 1365 | expect(cachesync).toHaveBeenCalled(); 1366 | expect(cachesync.callCount).toEqual(1); 1367 | 1368 | server.respond(); 1369 | 1370 | // Ensure cachesync was not called on this second go around 1371 | expect(cachesync.callCount).toEqual(1); 1372 | 1373 | expect(sync).toHaveBeenCalled(); 1374 | expect(sync.callCount).toEqual(2); 1375 | 1376 | expect(success.calls[0].args[0]).toEqual(collection); 1377 | expect(success.calls[0].args[1]).toEqual(collectionResponse); 1378 | }); 1379 | }); 1380 | 1381 | it('triggers progress on the promise on cache hit', function() { 1382 | var progress = jasmine.createSpy('progeress'); 1383 | var promise = collection.fetch({ prefill: true }).progress(progress); 1384 | 1385 | waitsFor(promiseNotified(promise)); 1386 | 1387 | runs(function() { 1388 | expect(progress).toHaveBeenCalledWith(collection); 1389 | }); 1390 | }); 1391 | 1392 | it('fulfills the promise on AJAX success', function() { 1393 | var success = jasmine.createSpy('success'); 1394 | collection.fetch({ prefill: true }).done(success); 1395 | server.respond(); 1396 | 1397 | expect(success.calls[0].args[0]).toEqual(collection); 1398 | expect(success.calls[0].args[1]).toEqual(collectionResponse); 1399 | }); 1400 | }); 1401 | 1402 | describe('with prefillExpires: 1000 option', function() { 1403 | var cacheData; 1404 | 1405 | beforeEach(function() { 1406 | cacheData = [ { cheese: 'pickle' } ]; 1407 | }); 1408 | 1409 | it('returns value if cached value is neither expired nor prefill expired', function() { 1410 | Backbone.fetchCache._cache[collection.url] = { 1411 | value: cacheData, 1412 | expires: (new Date()).getTime() + (5 * 60 * 1000), 1413 | prefillExpires: (new Date()).getTime() + (5 * 60 * 1000) 1414 | }; 1415 | 1416 | var promise = collection.fetch({ 1417 | prefill: true, 1418 | prefillExpires: 1000 1419 | }); 1420 | 1421 | waitsFor(promiseComplete(promise)); 1422 | 1423 | runs(function() { 1424 | expect(collection.toJSON()).toEqual(cacheData); 1425 | }); 1426 | }); 1427 | 1428 | it('fetches value if cached value is valid but prefill expired', function() { 1429 | Backbone.fetchCache._cache[collection.url] = { 1430 | value: cacheData, 1431 | expires: (new Date()).getTime() + (5 * 60 * 1000), 1432 | prefillExpires: (new Date()).getTime() - (5 * 60 * 1000) 1433 | }; 1434 | 1435 | var promise = collection.fetch({ 1436 | prefill: true, 1437 | prefillExpires: 1000 1438 | }); 1439 | 1440 | waitsFor(promiseComplete(promise)); 1441 | server.respond(); 1442 | 1443 | runs(function() { 1444 | expect(collection.toJSON()).toEqual(collectionResponse); 1445 | }); 1446 | }); 1447 | 1448 | it('triggers progress if cached value is valid but prefill expired', function() { 1449 | Backbone.fetchCache._cache[collection.url] = { 1450 | value: cacheData, 1451 | expires: (new Date()).getTime() + (5 * 60 * 1000), 1452 | prefillExpires: (new Date()).getTime() - (5 * 60 * 1000) 1453 | }; 1454 | var progress = jasmine.createSpy('progress'); 1455 | 1456 | var promise = collection.fetch({ 1457 | prefill: true, 1458 | prefillExpires: 1000 1459 | }).progress(progress); 1460 | 1461 | waitsFor(promiseNotified(promise)); 1462 | 1463 | runs(function() { 1464 | expect(progress).toHaveBeenCalledWith(collection); 1465 | }); 1466 | }); 1467 | 1468 | it("fetches value if value isn't cached", function() { 1469 | Backbone.fetchCache._cache = {}; 1470 | 1471 | var promise = collection.fetch({ 1472 | prefill: true, 1473 | prefillExpires: 1000 1474 | }); 1475 | 1476 | waitsFor(promiseComplete(promise)); 1477 | server.respond(); 1478 | 1479 | runs(function() { 1480 | expect(collection.toJSON()).toEqual(collectionResponse); 1481 | }); 1482 | }); 1483 | 1484 | it('fetches value if cached value is expired', function() { 1485 | Backbone.fetchCache._cache[collection.url] = { 1486 | value: cacheData, 1487 | expires: (new Date()).getTime() - (5 * 60 * 1000), 1488 | prefillExpires: (new Date()).getTime() - (5 * 60 * 1000) 1489 | }; 1490 | 1491 | var promise = collection.fetch({ 1492 | prefill: true, 1493 | prefillExpires: 1000 1494 | }); 1495 | 1496 | waitsFor(promiseComplete(promise)); 1497 | server.respond(); 1498 | 1499 | runs(function() { 1500 | expect(collection.toJSON()).not.toEqual(cacheData); 1501 | expect(collection.toJSON()).toEqual(collectionResponse); 1502 | }); 1503 | }); 1504 | 1505 | it("sets the prefillExpires value if cached value doesn't exist", function() { 1506 | Backbone.fetchCache._cache = {}; 1507 | 1508 | var promise = collection.fetch({ 1509 | prefill: true, 1510 | prefillExpires: 1000 1511 | }); 1512 | 1513 | waitsFor(promiseComplete(promise)); 1514 | server.respond(); 1515 | 1516 | runs(function() { 1517 | expect(Backbone.fetchCache._cache[collection.url].prefillExpires / 100).toBeCloseTo(((new Date()).getTime() + 1000000) / 100, 0); 1518 | }); 1519 | }); 1520 | }); 1521 | 1522 | describe('with caching disabled', function(){ 1523 | beforeEach(function(){ 1524 | Backbone.fetchCache.enabled = false; 1525 | }); 1526 | 1527 | afterEach(function(){ 1528 | Backbone.fetchCache.enabled = true; 1529 | }); 1530 | 1531 | it("doesn't set cache", function(){ 1532 | collection.fetch({ cache: true }); 1533 | server.respond(); 1534 | expect(Backbone.fetchCache._cache[collection.url]) 1535 | .toBeUndefined(); 1536 | }); 1537 | 1538 | it("doesn't use cache", function(){ 1539 | Backbone.fetchCache._cache[collection.url] = { 1540 | value: cacheData, 1541 | expires: (new Date()).getTime() - (5* 60 * 1000) 1542 | }; 1543 | 1544 | collection.fetch({cache: true}); 1545 | server.respond(); 1546 | 1547 | expect(collection.toJSON()).not.toEqual(cacheData); 1548 | expect(collection.toJSON()).toEqual(collectionResponse); 1549 | }); 1550 | }); 1551 | 1552 | describe('with context option', function() { 1553 | var context; 1554 | 1555 | function setFoo() { 1556 | this.foo = 'bar'; 1557 | } 1558 | 1559 | beforeEach(function() { 1560 | context = {}; 1561 | }); 1562 | 1563 | describe('on AJAX success', function() { 1564 | it('resolves the promise with context', function() { 1565 | var done = jasmine.createSpy('done').andCallFake(setFoo); 1566 | var promise = collection.fetch({ 1567 | context: context 1568 | }); 1569 | 1570 | promise.done(done); 1571 | waitsFor(promiseComplete(promise)); 1572 | server.respond(); 1573 | 1574 | runs(function() { 1575 | expect(done).toHaveBeenCalled(); 1576 | expect(context.foo).toBe('bar'); 1577 | }); 1578 | }); 1579 | }); 1580 | 1581 | describe('on AJAX error', function() { 1582 | it('rejects the promise with context', function() { 1583 | var fail = jasmine.createSpy('fail').andCallFake(setFoo); 1584 | var promise = errorCollection.fetch({ 1585 | context: context 1586 | }); 1587 | 1588 | promise.fail(fail); 1589 | waitsFor(promiseComplete(promise)); 1590 | server.respond(); 1591 | 1592 | runs(function() { 1593 | expect(fail).toHaveBeenCalled(); 1594 | expect(context.foo).toBe('bar'); 1595 | }); 1596 | }); 1597 | }); 1598 | 1599 | describe('on a cache hit', function() { 1600 | beforeEach(function() { 1601 | cacheData = { cheese: 'pickle' }; 1602 | Backbone.fetchCache._cache[collection.url] = { 1603 | value: cacheData, 1604 | expires: (new Date()).getTime() + (5* 60 * 1000) 1605 | }; 1606 | }); 1607 | 1608 | it('resolves the promise with context', function() { 1609 | var done = jasmine.createSpy('done').andCallFake(setFoo); 1610 | var promise = collection.fetch({ 1611 | cache: true, 1612 | context: context 1613 | }); 1614 | 1615 | promise.done(done); 1616 | waitsFor(promiseComplete(promise)); 1617 | server.respond(); 1618 | 1619 | runs(function() { 1620 | expect(done).toHaveBeenCalled(); 1621 | expect(context.foo).toBe('bar'); 1622 | }); 1623 | }); 1624 | 1625 | it('calls the prefillSuccess callback with context', function() { 1626 | var prefillSuccess = jasmine.createSpy('prefillSuccess').andCallFake(setFoo); 1627 | var promise = collection.fetch({ 1628 | context: context, 1629 | prefill: true, 1630 | prefillSuccess: prefillSuccess 1631 | }); 1632 | 1633 | waitsFor(promiseNotified(promise)); 1634 | 1635 | runs(function() { 1636 | expect(prefillSuccess).toHaveBeenCalled(); 1637 | expect(context.foo).toBe('bar'); 1638 | }); 1639 | }); 1640 | 1641 | it('triggers progress on the promise with context', function() { 1642 | var progress = jasmine.createSpy('progress').andCallFake(setFoo); 1643 | var promise = collection.fetch({ 1644 | context: context, 1645 | prefill: true 1646 | }); 1647 | 1648 | promise.progress(progress); 1649 | waitsFor(promiseNotified(promise)); 1650 | 1651 | runs(function() { 1652 | expect(progress).toHaveBeenCalled(); 1653 | expect(context.foo).toBe('bar'); 1654 | }); 1655 | }); 1656 | 1657 | it('calls the success callback with context', function() { 1658 | var success = jasmine.createSpy('success').andCallFake(setFoo); 1659 | var promise = collection.fetch({ 1660 | cache: true, 1661 | context: context, 1662 | success: success 1663 | }); 1664 | 1665 | waitsFor(promiseComplete(promise)); 1666 | server.respond(); 1667 | 1668 | runs(function() { 1669 | expect(success).toHaveBeenCalled(); 1670 | expect(context.foo).toBe('bar'); 1671 | }); 1672 | }); 1673 | }); 1674 | }); 1675 | }); 1676 | }); 1677 | describe('Prefix', function() { 1678 | beforeEach(function() { 1679 | Backbone.fetchCache.getLocalStorageKey = function() { 1680 | return 'backboneCache_user1'; 1681 | }; 1682 | }); 1683 | 1684 | it('get prefix', function() { 1685 | expect(Backbone.fetchCache.getLocalStorageKey()).toEqual('backboneCache_user1'); 1686 | }); 1687 | 1688 | it('set localStorage', function() { 1689 | var cache = Backbone.fetchCache._cache = { 1690 | '/url1': { expires: false, value: { bacon: 'sandwich' } }, 1691 | '/url2': { expires: false, value: { egg: 'roll' } } 1692 | }; 1693 | Backbone.fetchCache.setLocalStorage(); 1694 | expect(localStorage.getItem('backboneCache_user1')).toEqual(JSON.stringify(cache)); 1695 | }); 1696 | 1697 | it('get localStorage', function() { 1698 | var cache = { 1699 | '/url1': { expires: false, value: { bacon: 'sandwich' } }, 1700 | '/url2': { expires: false, value: { egg: 'roll' } } 1701 | }; 1702 | localStorage.setItem('backboneCache_user1', JSON.stringify(cache)); 1703 | Backbone.fetchCache.getLocalStorage(); 1704 | expect(Backbone.fetchCache._cache).toEqual(cache); 1705 | }); 1706 | 1707 | it('get localStorage for several users', function() { 1708 | Backbone.fetchCache.getLocalStorageKey = function() { 1709 | return 'backboneCache_user2'; 1710 | }; 1711 | var cache = Backbone.fetchCache._cache = { 1712 | '/url1': { expires: true, value: { vegetables: 'tomato' } }, 1713 | '/url2': { expires: true, value: { egg: 'roll' } } 1714 | }; 1715 | localStorage.setItem('backboneCache_user1', ''); 1716 | Backbone.fetchCache.setLocalStorage(); 1717 | expect(localStorage.getItem('backboneCache_user2')).toEqual(JSON.stringify(cache)); 1718 | expect(localStorage.getItem('backboneCache_user1')).toEqual(''); 1719 | }); 1720 | }); 1721 | }); 1722 | -------------------------------------------------------------------------------- /spec/lib/backbone.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 1.0.0 2 | 3 | // (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc. 4 | // Backbone may be freely distributed under the MIT license. 5 | // For all details and documentation: 6 | // http://backbonejs.org 7 | 8 | (function(){ 9 | 10 | // Initial Setup 11 | // ------------- 12 | 13 | // Save a reference to the global object (`window` in the browser, `exports` 14 | // on the server). 15 | var root = this; 16 | 17 | // Save the previous value of the `Backbone` variable, so that it can be 18 | // restored later on, if `noConflict` is used. 19 | var previousBackbone = root.Backbone; 20 | 21 | // Create local references to array methods we'll want to use later. 22 | var array = []; 23 | var push = array.push; 24 | var slice = array.slice; 25 | var splice = array.splice; 26 | 27 | // The top-level namespace. All public Backbone classes and modules will 28 | // be attached to this. Exported for both the browser and the server. 29 | var Backbone; 30 | if (typeof exports !== 'undefined') { 31 | Backbone = exports; 32 | } else { 33 | Backbone = root.Backbone = {}; 34 | } 35 | 36 | // Current version of the library. Keep in sync with `package.json`. 37 | Backbone.VERSION = '1.0.0'; 38 | 39 | // Require Underscore, if we're on the server, and it's not already present. 40 | var _ = root._; 41 | if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); 42 | 43 | // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns 44 | // the `$` variable. 45 | Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$; 46 | 47 | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable 48 | // to its previous owner. Returns a reference to this Backbone object. 49 | Backbone.noConflict = function() { 50 | root.Backbone = previousBackbone; 51 | return this; 52 | }; 53 | 54 | // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option 55 | // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and 56 | // set a `X-Http-Method-Override` header. 57 | Backbone.emulateHTTP = false; 58 | 59 | // Turn on `emulateJSON` to support legacy servers that can't deal with direct 60 | // `application/json` requests ... will encode the body as 61 | // `application/x-www-form-urlencoded` instead and will send the model in a 62 | // form param named `model`. 63 | Backbone.emulateJSON = false; 64 | 65 | // Backbone.Events 66 | // --------------- 67 | 68 | // A module that can be mixed in to *any object* in order to provide it with 69 | // custom events. You may bind with `on` or remove with `off` callback 70 | // functions to an event; `trigger`-ing an event fires all callbacks in 71 | // succession. 72 | // 73 | // var object = {}; 74 | // _.extend(object, Backbone.Events); 75 | // object.on('expand', function(){ alert('expanded'); }); 76 | // object.trigger('expand'); 77 | // 78 | var Events = Backbone.Events = { 79 | 80 | // Bind an event to a `callback` function. Passing `"all"` will bind 81 | // the callback to all events fired. 82 | on: function(name, callback, context) { 83 | if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; 84 | this._events || (this._events = {}); 85 | var events = this._events[name] || (this._events[name] = []); 86 | events.push({callback: callback, context: context, ctx: context || this}); 87 | return this; 88 | }, 89 | 90 | // Bind an event to only be triggered a single time. After the first time 91 | // the callback is invoked, it will be removed. 92 | once: function(name, callback, context) { 93 | if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; 94 | var self = this; 95 | var once = _.once(function() { 96 | self.off(name, once); 97 | callback.apply(this, arguments); 98 | }); 99 | once._callback = callback; 100 | return this.on(name, once, context); 101 | }, 102 | 103 | // Remove one or many callbacks. If `context` is null, removes all 104 | // callbacks with that function. If `callback` is null, removes all 105 | // callbacks for the event. If `name` is null, removes all bound 106 | // callbacks for all events. 107 | off: function(name, callback, context) { 108 | var retain, ev, events, names, i, l, j, k; 109 | if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; 110 | if (!name && !callback && !context) { 111 | this._events = {}; 112 | return this; 113 | } 114 | 115 | names = name ? [name] : _.keys(this._events); 116 | for (i = 0, l = names.length; i < l; i++) { 117 | name = names[i]; 118 | if (events = this._events[name]) { 119 | this._events[name] = retain = []; 120 | if (callback || context) { 121 | for (j = 0, k = events.length; j < k; j++) { 122 | ev = events[j]; 123 | if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || 124 | (context && context !== ev.context)) { 125 | retain.push(ev); 126 | } 127 | } 128 | } 129 | if (!retain.length) delete this._events[name]; 130 | } 131 | } 132 | 133 | return this; 134 | }, 135 | 136 | // Trigger one or many events, firing all bound callbacks. Callbacks are 137 | // passed the same arguments as `trigger` is, apart from the event name 138 | // (unless you're listening on `"all"`, which will cause your callback to 139 | // receive the true name of the event as the first argument). 140 | trigger: function(name) { 141 | if (!this._events) return this; 142 | var args = slice.call(arguments, 1); 143 | if (!eventsApi(this, 'trigger', name, args)) return this; 144 | var events = this._events[name]; 145 | var allEvents = this._events.all; 146 | if (events) triggerEvents(events, args); 147 | if (allEvents) triggerEvents(allEvents, arguments); 148 | return this; 149 | }, 150 | 151 | // Tell this object to stop listening to either specific events ... or 152 | // to every object it's currently listening to. 153 | stopListening: function(obj, name, callback) { 154 | var listeners = this._listeners; 155 | if (!listeners) return this; 156 | var deleteListener = !name && !callback; 157 | if (typeof name === 'object') callback = this; 158 | if (obj) (listeners = {})[obj._listenerId] = obj; 159 | for (var id in listeners) { 160 | listeners[id].off(name, callback, this); 161 | if (deleteListener) delete this._listeners[id]; 162 | } 163 | return this; 164 | } 165 | 166 | }; 167 | 168 | // Regular expression used to split event strings. 169 | var eventSplitter = /\s+/; 170 | 171 | // Implement fancy features of the Events API such as multiple event 172 | // names `"change blur"` and jQuery-style event maps `{change: action}` 173 | // in terms of the existing API. 174 | var eventsApi = function(obj, action, name, rest) { 175 | if (!name) return true; 176 | 177 | // Handle event maps. 178 | if (typeof name === 'object') { 179 | for (var key in name) { 180 | obj[action].apply(obj, [key, name[key]].concat(rest)); 181 | } 182 | return false; 183 | } 184 | 185 | // Handle space separated event names. 186 | if (eventSplitter.test(name)) { 187 | var names = name.split(eventSplitter); 188 | for (var i = 0, l = names.length; i < l; i++) { 189 | obj[action].apply(obj, [names[i]].concat(rest)); 190 | } 191 | return false; 192 | } 193 | 194 | return true; 195 | }; 196 | 197 | // A difficult-to-believe, but optimized internal dispatch function for 198 | // triggering events. Tries to keep the usual cases speedy (most internal 199 | // Backbone events have 3 arguments). 200 | var triggerEvents = function(events, args) { 201 | var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; 202 | switch (args.length) { 203 | case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; 204 | case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; 205 | case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; 206 | case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; 207 | default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); 208 | } 209 | }; 210 | 211 | var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; 212 | 213 | // Inversion-of-control versions of `on` and `once`. Tell *this* object to 214 | // listen to an event in another object ... keeping track of what it's 215 | // listening to. 216 | _.each(listenMethods, function(implementation, method) { 217 | Events[method] = function(obj, name, callback) { 218 | var listeners = this._listeners || (this._listeners = {}); 219 | var id = obj._listenerId || (obj._listenerId = _.uniqueId('l')); 220 | listeners[id] = obj; 221 | if (typeof name === 'object') callback = this; 222 | obj[implementation](name, callback, this); 223 | return this; 224 | }; 225 | }); 226 | 227 | // Aliases for backwards compatibility. 228 | Events.bind = Events.on; 229 | Events.unbind = Events.off; 230 | 231 | // Allow the `Backbone` object to serve as a global event bus, for folks who 232 | // want global "pubsub" in a convenient place. 233 | _.extend(Backbone, Events); 234 | 235 | // Backbone.Model 236 | // -------------- 237 | 238 | // Backbone **Models** are the basic data object in the framework -- 239 | // frequently representing a row in a table in a database on your server. 240 | // A discrete chunk of data and a bunch of useful, related methods for 241 | // performing computations and transformations on that data. 242 | 243 | // Create a new model with the specified attributes. A client id (`cid`) 244 | // is automatically generated and assigned for you. 245 | var Model = Backbone.Model = function(attributes, options) { 246 | var defaults; 247 | var attrs = attributes || {}; 248 | options || (options = {}); 249 | this.cid = _.uniqueId('c'); 250 | this.attributes = {}; 251 | _.extend(this, _.pick(options, modelOptions)); 252 | if (options.parse) attrs = this.parse(attrs, options) || {}; 253 | if (defaults = _.result(this, 'defaults')) { 254 | attrs = _.defaults({}, attrs, defaults); 255 | } 256 | this.set(attrs, options); 257 | this.changed = {}; 258 | this.initialize.apply(this, arguments); 259 | }; 260 | 261 | // A list of options to be attached directly to the model, if provided. 262 | var modelOptions = ['url', 'urlRoot', 'collection']; 263 | 264 | // Attach all inheritable methods to the Model prototype. 265 | _.extend(Model.prototype, Events, { 266 | 267 | // A hash of attributes whose current and previous value differ. 268 | changed: null, 269 | 270 | // The value returned during the last failed validation. 271 | validationError: null, 272 | 273 | // The default name for the JSON `id` attribute is `"id"`. MongoDB and 274 | // CouchDB users may want to set this to `"_id"`. 275 | idAttribute: 'id', 276 | 277 | // Initialize is an empty function by default. Override it with your own 278 | // initialization logic. 279 | initialize: function(){}, 280 | 281 | // Return a copy of the model's `attributes` object. 282 | toJSON: function(options) { 283 | return _.clone(this.attributes); 284 | }, 285 | 286 | // Proxy `Backbone.sync` by default -- but override this if you need 287 | // custom syncing semantics for *this* particular model. 288 | sync: function() { 289 | return Backbone.sync.apply(this, arguments); 290 | }, 291 | 292 | // Get the value of an attribute. 293 | get: function(attr) { 294 | return this.attributes[attr]; 295 | }, 296 | 297 | // Get the HTML-escaped value of an attribute. 298 | escape: function(attr) { 299 | return _.escape(this.get(attr)); 300 | }, 301 | 302 | // Returns `true` if the attribute contains a value that is not null 303 | // or undefined. 304 | has: function(attr) { 305 | return this.get(attr) != null; 306 | }, 307 | 308 | // Set a hash of model attributes on the object, firing `"change"`. This is 309 | // the core primitive operation of a model, updating the data and notifying 310 | // anyone who needs to know about the change in state. The heart of the beast. 311 | set: function(key, val, options) { 312 | var attr, attrs, unset, changes, silent, changing, prev, current; 313 | if (key == null) return this; 314 | 315 | // Handle both `"key", value` and `{key: value}` -style arguments. 316 | if (typeof key === 'object') { 317 | attrs = key; 318 | options = val; 319 | } else { 320 | (attrs = {})[key] = val; 321 | } 322 | 323 | options || (options = {}); 324 | 325 | // Run validation. 326 | if (!this._validate(attrs, options)) return false; 327 | 328 | // Extract attributes and options. 329 | unset = options.unset; 330 | silent = options.silent; 331 | changes = []; 332 | changing = this._changing; 333 | this._changing = true; 334 | 335 | if (!changing) { 336 | this._previousAttributes = _.clone(this.attributes); 337 | this.changed = {}; 338 | } 339 | current = this.attributes, prev = this._previousAttributes; 340 | 341 | // Check for changes of `id`. 342 | if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; 343 | 344 | // For each `set` attribute, update or delete the current value. 345 | for (attr in attrs) { 346 | val = attrs[attr]; 347 | if (!_.isEqual(current[attr], val)) changes.push(attr); 348 | if (!_.isEqual(prev[attr], val)) { 349 | this.changed[attr] = val; 350 | } else { 351 | delete this.changed[attr]; 352 | } 353 | unset ? delete current[attr] : current[attr] = val; 354 | } 355 | 356 | // Trigger all relevant attribute changes. 357 | if (!silent) { 358 | if (changes.length) this._pending = true; 359 | for (var i = 0, l = changes.length; i < l; i++) { 360 | this.trigger('change:' + changes[i], this, current[changes[i]], options); 361 | } 362 | } 363 | 364 | // You might be wondering why there's a `while` loop here. Changes can 365 | // be recursively nested within `"change"` events. 366 | if (changing) return this; 367 | if (!silent) { 368 | while (this._pending) { 369 | this._pending = false; 370 | this.trigger('change', this, options); 371 | } 372 | } 373 | this._pending = false; 374 | this._changing = false; 375 | return this; 376 | }, 377 | 378 | // Remove an attribute from the model, firing `"change"`. `unset` is a noop 379 | // if the attribute doesn't exist. 380 | unset: function(attr, options) { 381 | return this.set(attr, void 0, _.extend({}, options, {unset: true})); 382 | }, 383 | 384 | // Clear all attributes on the model, firing `"change"`. 385 | clear: function(options) { 386 | var attrs = {}; 387 | for (var key in this.attributes) attrs[key] = void 0; 388 | return this.set(attrs, _.extend({}, options, {unset: true})); 389 | }, 390 | 391 | // Determine if the model has changed since the last `"change"` event. 392 | // If you specify an attribute name, determine if that attribute has changed. 393 | hasChanged: function(attr) { 394 | if (attr == null) return !_.isEmpty(this.changed); 395 | return _.has(this.changed, attr); 396 | }, 397 | 398 | // Return an object containing all the attributes that have changed, or 399 | // false if there are no changed attributes. Useful for determining what 400 | // parts of a view need to be updated and/or what attributes need to be 401 | // persisted to the server. Unset attributes will be set to undefined. 402 | // You can also pass an attributes object to diff against the model, 403 | // determining if there *would be* a change. 404 | changedAttributes: function(diff) { 405 | if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; 406 | var val, changed = false; 407 | var old = this._changing ? this._previousAttributes : this.attributes; 408 | for (var attr in diff) { 409 | if (_.isEqual(old[attr], (val = diff[attr]))) continue; 410 | (changed || (changed = {}))[attr] = val; 411 | } 412 | return changed; 413 | }, 414 | 415 | // Get the previous value of an attribute, recorded at the time the last 416 | // `"change"` event was fired. 417 | previous: function(attr) { 418 | if (attr == null || !this._previousAttributes) return null; 419 | return this._previousAttributes[attr]; 420 | }, 421 | 422 | // Get all of the attributes of the model at the time of the previous 423 | // `"change"` event. 424 | previousAttributes: function() { 425 | return _.clone(this._previousAttributes); 426 | }, 427 | 428 | // Fetch the model from the server. If the server's representation of the 429 | // model differs from its current attributes, they will be overridden, 430 | // triggering a `"change"` event. 431 | fetch: function(options) { 432 | options = options ? _.clone(options) : {}; 433 | if (options.parse === void 0) options.parse = true; 434 | var model = this; 435 | var success = options.success; 436 | options.success = function(resp) { 437 | if (!model.set(model.parse(resp, options), options)) return false; 438 | if (success) success(model, resp, options); 439 | model.trigger('sync', model, resp, options); 440 | }; 441 | wrapError(this, options); 442 | return this.sync('read', this, options); 443 | }, 444 | 445 | // Set a hash of model attributes, and sync the model to the server. 446 | // If the server returns an attributes hash that differs, the model's 447 | // state will be `set` again. 448 | save: function(key, val, options) { 449 | var attrs, method, xhr, attributes = this.attributes; 450 | 451 | // Handle both `"key", value` and `{key: value}` -style arguments. 452 | if (key == null || typeof key === 'object') { 453 | attrs = key; 454 | options = val; 455 | } else { 456 | (attrs = {})[key] = val; 457 | } 458 | 459 | // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`. 460 | if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false; 461 | 462 | options = _.extend({validate: true}, options); 463 | 464 | // Do not persist invalid models. 465 | if (!this._validate(attrs, options)) return false; 466 | 467 | // Set temporary attributes if `{wait: true}`. 468 | if (attrs && options.wait) { 469 | this.attributes = _.extend({}, attributes, attrs); 470 | } 471 | 472 | // After a successful server-side save, the client is (optionally) 473 | // updated with the server-side state. 474 | if (options.parse === void 0) options.parse = true; 475 | var model = this; 476 | var success = options.success; 477 | options.success = function(resp) { 478 | // Ensure attributes are restored during synchronous saves. 479 | model.attributes = attributes; 480 | var serverAttrs = model.parse(resp, options); 481 | if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); 482 | if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { 483 | return false; 484 | } 485 | if (success) success(model, resp, options); 486 | model.trigger('sync', model, resp, options); 487 | }; 488 | wrapError(this, options); 489 | 490 | method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); 491 | if (method === 'patch') options.attrs = attrs; 492 | xhr = this.sync(method, this, options); 493 | 494 | // Restore attributes. 495 | if (attrs && options.wait) this.attributes = attributes; 496 | 497 | return xhr; 498 | }, 499 | 500 | // Destroy this model on the server if it was already persisted. 501 | // Optimistically removes the model from its collection, if it has one. 502 | // If `wait: true` is passed, waits for the server to respond before removal. 503 | destroy: function(options) { 504 | options = options ? _.clone(options) : {}; 505 | var model = this; 506 | var success = options.success; 507 | 508 | var destroy = function() { 509 | model.trigger('destroy', model, model.collection, options); 510 | }; 511 | 512 | options.success = function(resp) { 513 | if (options.wait || model.isNew()) destroy(); 514 | if (success) success(model, resp, options); 515 | if (!model.isNew()) model.trigger('sync', model, resp, options); 516 | }; 517 | 518 | if (this.isNew()) { 519 | options.success(); 520 | return false; 521 | } 522 | wrapError(this, options); 523 | 524 | var xhr = this.sync('delete', this, options); 525 | if (!options.wait) destroy(); 526 | return xhr; 527 | }, 528 | 529 | // Default URL for the model's representation on the server -- if you're 530 | // using Backbone's restful methods, override this to change the endpoint 531 | // that will be called. 532 | url: function() { 533 | var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); 534 | if (this.isNew()) return base; 535 | return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); 536 | }, 537 | 538 | // **parse** converts a response into the hash of attributes to be `set` on 539 | // the model. The default implementation is just to pass the response along. 540 | parse: function(resp, options) { 541 | return resp; 542 | }, 543 | 544 | // Create a new model with identical attributes to this one. 545 | clone: function() { 546 | return new this.constructor(this.attributes); 547 | }, 548 | 549 | // A model is new if it has never been saved to the server, and lacks an id. 550 | isNew: function() { 551 | return this.id == null; 552 | }, 553 | 554 | // Check if the model is currently in a valid state. 555 | isValid: function(options) { 556 | return this._validate({}, _.extend(options || {}, { validate: true })); 557 | }, 558 | 559 | // Run validation against the next complete set of model attributes, 560 | // returning `true` if all is well. Otherwise, fire an `"invalid"` event. 561 | _validate: function(attrs, options) { 562 | if (!options.validate || !this.validate) return true; 563 | attrs = _.extend({}, this.attributes, attrs); 564 | var error = this.validationError = this.validate(attrs, options) || null; 565 | if (!error) return true; 566 | this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error})); 567 | return false; 568 | } 569 | 570 | }); 571 | 572 | // Underscore methods that we want to implement on the Model. 573 | var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; 574 | 575 | // Mix in each Underscore method as a proxy to `Model#attributes`. 576 | _.each(modelMethods, function(method) { 577 | Model.prototype[method] = function() { 578 | var args = slice.call(arguments); 579 | args.unshift(this.attributes); 580 | return _[method].apply(_, args); 581 | }; 582 | }); 583 | 584 | // Backbone.Collection 585 | // ------------------- 586 | 587 | // If models tend to represent a single row of data, a Backbone Collection is 588 | // more analagous to a table full of data ... or a small slice or page of that 589 | // table, or a collection of rows that belong together for a particular reason 590 | // -- all of the messages in this particular folder, all of the documents 591 | // belonging to this particular author, and so on. Collections maintain 592 | // indexes of their models, both in order, and for lookup by `id`. 593 | 594 | // Create a new **Collection**, perhaps to contain a specific type of `model`. 595 | // If a `comparator` is specified, the Collection will maintain 596 | // its models in sort order, as they're added and removed. 597 | var Collection = Backbone.Collection = function(models, options) { 598 | options || (options = {}); 599 | if (options.url) this.url = options.url; 600 | if (options.model) this.model = options.model; 601 | if (options.comparator !== void 0) this.comparator = options.comparator; 602 | this._reset(); 603 | this.initialize.apply(this, arguments); 604 | if (models) this.reset(models, _.extend({silent: true}, options)); 605 | }; 606 | 607 | // Default options for `Collection#set`. 608 | var setOptions = {add: true, remove: true, merge: true}; 609 | var addOptions = {add: true, merge: false, remove: false}; 610 | 611 | // Define the Collection's inheritable methods. 612 | _.extend(Collection.prototype, Events, { 613 | 614 | // The default model for a collection is just a **Backbone.Model**. 615 | // This should be overridden in most cases. 616 | model: Model, 617 | 618 | // Initialize is an empty function by default. Override it with your own 619 | // initialization logic. 620 | initialize: function(){}, 621 | 622 | // The JSON representation of a Collection is an array of the 623 | // models' attributes. 624 | toJSON: function(options) { 625 | return this.map(function(model){ return model.toJSON(options); }); 626 | }, 627 | 628 | // Proxy `Backbone.sync` by default. 629 | sync: function() { 630 | return Backbone.sync.apply(this, arguments); 631 | }, 632 | 633 | // Add a model, or list of models to the set. 634 | add: function(models, options) { 635 | return this.set(models, _.defaults(options || {}, addOptions)); 636 | }, 637 | 638 | // Remove a model, or a list of models from the set. 639 | remove: function(models, options) { 640 | models = _.isArray(models) ? models.slice() : [models]; 641 | options || (options = {}); 642 | var i, l, index, model; 643 | for (i = 0, l = models.length; i < l; i++) { 644 | model = this.get(models[i]); 645 | if (!model) continue; 646 | delete this._byId[model.id]; 647 | delete this._byId[model.cid]; 648 | index = this.indexOf(model); 649 | this.models.splice(index, 1); 650 | this.length--; 651 | if (!options.silent) { 652 | options.index = index; 653 | model.trigger('remove', model, this, options); 654 | } 655 | this._removeReference(model); 656 | } 657 | return this; 658 | }, 659 | 660 | // Update a collection by `set`-ing a new list of models, adding new ones, 661 | // removing models that are no longer present, and merging models that 662 | // already exist in the collection, as necessary. Similar to **Model#set**, 663 | // the core operation for updating the data contained by the collection. 664 | set: function(models, options) { 665 | options = _.defaults(options || {}, setOptions); 666 | if (options.parse) models = this.parse(models, options); 667 | if (!_.isArray(models)) models = models ? [models] : []; 668 | var i, l, model, attrs, existing, sort; 669 | var at = options.at; 670 | var sortable = this.comparator && (at == null) && options.sort !== false; 671 | var sortAttr = _.isString(this.comparator) ? this.comparator : null; 672 | var toAdd = [], toRemove = [], modelMap = {}; 673 | 674 | // Turn bare objects into model references, and prevent invalid models 675 | // from being added. 676 | for (i = 0, l = models.length; i < l; i++) { 677 | if (!(model = this._prepareModel(models[i], options))) continue; 678 | 679 | // If a duplicate is found, prevent it from being added and 680 | // optionally merge it into the existing model. 681 | if (existing = this.get(model)) { 682 | if (options.remove) modelMap[existing.cid] = true; 683 | if (options.merge) { 684 | existing.set(model.attributes, options); 685 | if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; 686 | } 687 | 688 | // This is a new model, push it to the `toAdd` list. 689 | } else if (options.add) { 690 | toAdd.push(model); 691 | 692 | // Listen to added models' events, and index models for lookup by 693 | // `id` and by `cid`. 694 | model.on('all', this._onModelEvent, this); 695 | this._byId[model.cid] = model; 696 | if (model.id != null) this._byId[model.id] = model; 697 | } 698 | } 699 | 700 | // Remove nonexistent models if appropriate. 701 | if (options.remove) { 702 | for (i = 0, l = this.length; i < l; ++i) { 703 | if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); 704 | } 705 | if (toRemove.length) this.remove(toRemove, options); 706 | } 707 | 708 | // See if sorting is needed, update `length` and splice in new models. 709 | if (toAdd.length) { 710 | if (sortable) sort = true; 711 | this.length += toAdd.length; 712 | if (at != null) { 713 | splice.apply(this.models, [at, 0].concat(toAdd)); 714 | } else { 715 | push.apply(this.models, toAdd); 716 | } 717 | } 718 | 719 | // Silently sort the collection if appropriate. 720 | if (sort) this.sort({silent: true}); 721 | 722 | if (options.silent) return this; 723 | 724 | // Trigger `add` events. 725 | for (i = 0, l = toAdd.length; i < l; i++) { 726 | (model = toAdd[i]).trigger('add', model, this, options); 727 | } 728 | 729 | // Trigger `sort` if the collection was sorted. 730 | if (sort) this.trigger('sort', this, options); 731 | return this; 732 | }, 733 | 734 | // When you have more items than you want to add or remove individually, 735 | // you can reset the entire set with a new list of models, without firing 736 | // any granular `add` or `remove` events. Fires `reset` when finished. 737 | // Useful for bulk operations and optimizations. 738 | reset: function(models, options) { 739 | options || (options = {}); 740 | for (var i = 0, l = this.models.length; i < l; i++) { 741 | this._removeReference(this.models[i]); 742 | } 743 | options.previousModels = this.models; 744 | this._reset(); 745 | this.add(models, _.extend({silent: true}, options)); 746 | if (!options.silent) this.trigger('reset', this, options); 747 | return this; 748 | }, 749 | 750 | // Add a model to the end of the collection. 751 | push: function(model, options) { 752 | model = this._prepareModel(model, options); 753 | this.add(model, _.extend({at: this.length}, options)); 754 | return model; 755 | }, 756 | 757 | // Remove a model from the end of the collection. 758 | pop: function(options) { 759 | var model = this.at(this.length - 1); 760 | this.remove(model, options); 761 | return model; 762 | }, 763 | 764 | // Add a model to the beginning of the collection. 765 | unshift: function(model, options) { 766 | model = this._prepareModel(model, options); 767 | this.add(model, _.extend({at: 0}, options)); 768 | return model; 769 | }, 770 | 771 | // Remove a model from the beginning of the collection. 772 | shift: function(options) { 773 | var model = this.at(0); 774 | this.remove(model, options); 775 | return model; 776 | }, 777 | 778 | // Slice out a sub-array of models from the collection. 779 | slice: function(begin, end) { 780 | return this.models.slice(begin, end); 781 | }, 782 | 783 | // Get a model from the set by id. 784 | get: function(obj) { 785 | if (obj == null) return void 0; 786 | return this._byId[obj.id != null ? obj.id : obj.cid || obj]; 787 | }, 788 | 789 | // Get the model at the given index. 790 | at: function(index) { 791 | return this.models[index]; 792 | }, 793 | 794 | // Return models with matching attributes. Useful for simple cases of 795 | // `filter`. 796 | where: function(attrs, first) { 797 | if (_.isEmpty(attrs)) return first ? void 0 : []; 798 | return this[first ? 'find' : 'filter'](function(model) { 799 | for (var key in attrs) { 800 | if (attrs[key] !== model.get(key)) return false; 801 | } 802 | return true; 803 | }); 804 | }, 805 | 806 | // Return the first model with matching attributes. Useful for simple cases 807 | // of `find`. 808 | findWhere: function(attrs) { 809 | return this.where(attrs, true); 810 | }, 811 | 812 | // Force the collection to re-sort itself. You don't need to call this under 813 | // normal circumstances, as the set will maintain sort order as each item 814 | // is added. 815 | sort: function(options) { 816 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); 817 | options || (options = {}); 818 | 819 | // Run sort based on type of `comparator`. 820 | if (_.isString(this.comparator) || this.comparator.length === 1) { 821 | this.models = this.sortBy(this.comparator, this); 822 | } else { 823 | this.models.sort(_.bind(this.comparator, this)); 824 | } 825 | 826 | if (!options.silent) this.trigger('sort', this, options); 827 | return this; 828 | }, 829 | 830 | // Figure out the smallest index at which a model should be inserted so as 831 | // to maintain order. 832 | sortedIndex: function(model, value, context) { 833 | value || (value = this.comparator); 834 | var iterator = _.isFunction(value) ? value : function(model) { 835 | return model.get(value); 836 | }; 837 | return _.sortedIndex(this.models, model, iterator, context); 838 | }, 839 | 840 | // Pluck an attribute from each model in the collection. 841 | pluck: function(attr) { 842 | return _.invoke(this.models, 'get', attr); 843 | }, 844 | 845 | // Fetch the default set of models for this collection, resetting the 846 | // collection when they arrive. If `reset: true` is passed, the response 847 | // data will be passed through the `reset` method instead of `set`. 848 | fetch: function(options) { 849 | options = options ? _.clone(options) : {}; 850 | if (options.parse === void 0) options.parse = true; 851 | var success = options.success; 852 | var collection = this; 853 | options.success = function(resp) { 854 | var method = options.reset ? 'reset' : 'set'; 855 | collection[method](resp, options); 856 | if (success) success(collection, resp, options); 857 | collection.trigger('sync', collection, resp, options); 858 | }; 859 | wrapError(this, options); 860 | return this.sync('read', this, options); 861 | }, 862 | 863 | // Create a new instance of a model in this collection. Add the model to the 864 | // collection immediately, unless `wait: true` is passed, in which case we 865 | // wait for the server to agree. 866 | create: function(model, options) { 867 | options = options ? _.clone(options) : {}; 868 | if (!(model = this._prepareModel(model, options))) return false; 869 | if (!options.wait) this.add(model, options); 870 | var collection = this; 871 | var success = options.success; 872 | options.success = function(resp) { 873 | if (options.wait) collection.add(model, options); 874 | if (success) success(model, resp, options); 875 | }; 876 | model.save(null, options); 877 | return model; 878 | }, 879 | 880 | // **parse** converts a response into a list of models to be added to the 881 | // collection. The default implementation is just to pass it through. 882 | parse: function(resp, options) { 883 | return resp; 884 | }, 885 | 886 | // Create a new collection with an identical list of models as this one. 887 | clone: function() { 888 | return new this.constructor(this.models); 889 | }, 890 | 891 | // Private method to reset all internal state. Called when the collection 892 | // is first initialized or reset. 893 | _reset: function() { 894 | this.length = 0; 895 | this.models = []; 896 | this._byId = {}; 897 | }, 898 | 899 | // Prepare a hash of attributes (or other model) to be added to this 900 | // collection. 901 | _prepareModel: function(attrs, options) { 902 | if (attrs instanceof Model) { 903 | if (!attrs.collection) attrs.collection = this; 904 | return attrs; 905 | } 906 | options || (options = {}); 907 | options.collection = this; 908 | var model = new this.model(attrs, options); 909 | if (!model._validate(attrs, options)) { 910 | this.trigger('invalid', this, attrs, options); 911 | return false; 912 | } 913 | return model; 914 | }, 915 | 916 | // Internal method to sever a model's ties to a collection. 917 | _removeReference: function(model) { 918 | if (this === model.collection) delete model.collection; 919 | model.off('all', this._onModelEvent, this); 920 | }, 921 | 922 | // Internal method called every time a model in the set fires an event. 923 | // Sets need to update their indexes when models change ids. All other 924 | // events simply proxy through. "add" and "remove" events that originate 925 | // in other collections are ignored. 926 | _onModelEvent: function(event, model, collection, options) { 927 | if ((event === 'add' || event === 'remove') && collection !== this) return; 928 | if (event === 'destroy') this.remove(model, options); 929 | if (model && event === 'change:' + model.idAttribute) { 930 | delete this._byId[model.previous(model.idAttribute)]; 931 | if (model.id != null) this._byId[model.id] = model; 932 | } 933 | this.trigger.apply(this, arguments); 934 | } 935 | 936 | }); 937 | 938 | // Underscore methods that we want to implement on the Collection. 939 | // 90% of the core usefulness of Backbone Collections is actually implemented 940 | // right here: 941 | var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 942 | 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 943 | 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 944 | 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 945 | 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 946 | 'isEmpty', 'chain']; 947 | 948 | // Mix in each Underscore method as a proxy to `Collection#models`. 949 | _.each(methods, function(method) { 950 | Collection.prototype[method] = function() { 951 | var args = slice.call(arguments); 952 | args.unshift(this.models); 953 | return _[method].apply(_, args); 954 | }; 955 | }); 956 | 957 | // Underscore methods that take a property name as an argument. 958 | var attributeMethods = ['groupBy', 'countBy', 'sortBy']; 959 | 960 | // Use attributes instead of properties. 961 | _.each(attributeMethods, function(method) { 962 | Collection.prototype[method] = function(value, context) { 963 | var iterator = _.isFunction(value) ? value : function(model) { 964 | return model.get(value); 965 | }; 966 | return _[method](this.models, iterator, context); 967 | }; 968 | }); 969 | 970 | // Backbone.View 971 | // ------------- 972 | 973 | // Backbone Views are almost more convention than they are actual code. A View 974 | // is simply a JavaScript object that represents a logical chunk of UI in the 975 | // DOM. This might be a single item, an entire list, a sidebar or panel, or 976 | // even the surrounding frame which wraps your whole app. Defining a chunk of 977 | // UI as a **View** allows you to define your DOM events declaratively, without 978 | // having to worry about render order ... and makes it easy for the view to 979 | // react to specific changes in the state of your models. 980 | 981 | // Creating a Backbone.View creates its initial element outside of the DOM, 982 | // if an existing element is not provided... 983 | var View = Backbone.View = function(options) { 984 | this.cid = _.uniqueId('view'); 985 | this._configure(options || {}); 986 | this._ensureElement(); 987 | this.initialize.apply(this, arguments); 988 | this.delegateEvents(); 989 | }; 990 | 991 | // Cached regex to split keys for `delegate`. 992 | var delegateEventSplitter = /^(\S+)\s*(.*)$/; 993 | 994 | // List of view options to be merged as properties. 995 | var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; 996 | 997 | // Set up all inheritable **Backbone.View** properties and methods. 998 | _.extend(View.prototype, Events, { 999 | 1000 | // The default `tagName` of a View's element is `"div"`. 1001 | tagName: 'div', 1002 | 1003 | // jQuery delegate for element lookup, scoped to DOM elements within the 1004 | // current view. This should be prefered to global lookups where possible. 1005 | $: function(selector) { 1006 | return this.$el.find(selector); 1007 | }, 1008 | 1009 | // Initialize is an empty function by default. Override it with your own 1010 | // initialization logic. 1011 | initialize: function(){}, 1012 | 1013 | // **render** is the core function that your view should override, in order 1014 | // to populate its element (`this.el`), with the appropriate HTML. The 1015 | // convention is for **render** to always return `this`. 1016 | render: function() { 1017 | return this; 1018 | }, 1019 | 1020 | // Remove this view by taking the element out of the DOM, and removing any 1021 | // applicable Backbone.Events listeners. 1022 | remove: function() { 1023 | this.$el.remove(); 1024 | this.stopListening(); 1025 | return this; 1026 | }, 1027 | 1028 | // Change the view's element (`this.el` property), including event 1029 | // re-delegation. 1030 | setElement: function(element, delegate) { 1031 | if (this.$el) this.undelegateEvents(); 1032 | this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); 1033 | this.el = this.$el[0]; 1034 | if (delegate !== false) this.delegateEvents(); 1035 | return this; 1036 | }, 1037 | 1038 | // Set callbacks, where `this.events` is a hash of 1039 | // 1040 | // *{"event selector": "callback"}* 1041 | // 1042 | // { 1043 | // 'mousedown .title': 'edit', 1044 | // 'click .button': 'save' 1045 | // 'click .open': function(e) { ... } 1046 | // } 1047 | // 1048 | // pairs. Callbacks will be bound to the view, with `this` set properly. 1049 | // Uses event delegation for efficiency. 1050 | // Omitting the selector binds the event to `this.el`. 1051 | // This only works for delegate-able events: not `focus`, `blur`, and 1052 | // not `change`, `submit`, and `reset` in Internet Explorer. 1053 | delegateEvents: function(events) { 1054 | if (!(events || (events = _.result(this, 'events')))) return this; 1055 | this.undelegateEvents(); 1056 | for (var key in events) { 1057 | var method = events[key]; 1058 | if (!_.isFunction(method)) method = this[events[key]]; 1059 | if (!method) continue; 1060 | 1061 | var match = key.match(delegateEventSplitter); 1062 | var eventName = match[1], selector = match[2]; 1063 | method = _.bind(method, this); 1064 | eventName += '.delegateEvents' + this.cid; 1065 | if (selector === '') { 1066 | this.$el.on(eventName, method); 1067 | } else { 1068 | this.$el.on(eventName, selector, method); 1069 | } 1070 | } 1071 | return this; 1072 | }, 1073 | 1074 | // Clears all callbacks previously bound to the view with `delegateEvents`. 1075 | // You usually don't need to use this, but may wish to if you have multiple 1076 | // Backbone views attached to the same DOM element. 1077 | undelegateEvents: function() { 1078 | this.$el.off('.delegateEvents' + this.cid); 1079 | return this; 1080 | }, 1081 | 1082 | // Performs the initial configuration of a View with a set of options. 1083 | // Keys with special meaning *(e.g. model, collection, id, className)* are 1084 | // attached directly to the view. See `viewOptions` for an exhaustive 1085 | // list. 1086 | _configure: function(options) { 1087 | if (this.options) options = _.extend({}, _.result(this, 'options'), options); 1088 | _.extend(this, _.pick(options, viewOptions)); 1089 | this.options = options; 1090 | }, 1091 | 1092 | // Ensure that the View has a DOM element to render into. 1093 | // If `this.el` is a string, pass it through `$()`, take the first 1094 | // matching element, and re-assign it to `el`. Otherwise, create 1095 | // an element from the `id`, `className` and `tagName` properties. 1096 | _ensureElement: function() { 1097 | if (!this.el) { 1098 | var attrs = _.extend({}, _.result(this, 'attributes')); 1099 | if (this.id) attrs.id = _.result(this, 'id'); 1100 | if (this.className) attrs['class'] = _.result(this, 'className'); 1101 | var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); 1102 | this.setElement($el, false); 1103 | } else { 1104 | this.setElement(_.result(this, 'el'), false); 1105 | } 1106 | } 1107 | 1108 | }); 1109 | 1110 | // Backbone.sync 1111 | // ------------- 1112 | 1113 | // Override this function to change the manner in which Backbone persists 1114 | // models to the server. You will be passed the type of request, and the 1115 | // model in question. By default, makes a RESTful Ajax request 1116 | // to the model's `url()`. Some possible customizations could be: 1117 | // 1118 | // * Use `setTimeout` to batch rapid-fire updates into a single request. 1119 | // * Send up the models as XML instead of JSON. 1120 | // * Persist models via WebSockets instead of Ajax. 1121 | // 1122 | // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests 1123 | // as `POST`, with a `_method` parameter containing the true HTTP method, 1124 | // as well as all requests with the body as `application/x-www-form-urlencoded` 1125 | // instead of `application/json` with the model in a param named `model`. 1126 | // Useful when interfacing with server-side languages like **PHP** that make 1127 | // it difficult to read the body of `PUT` requests. 1128 | Backbone.sync = function(method, model, options) { 1129 | var type = methodMap[method]; 1130 | 1131 | // Default options, unless specified. 1132 | _.defaults(options || (options = {}), { 1133 | emulateHTTP: Backbone.emulateHTTP, 1134 | emulateJSON: Backbone.emulateJSON 1135 | }); 1136 | 1137 | // Default JSON-request options. 1138 | var params = {type: type, dataType: 'json'}; 1139 | 1140 | // Ensure that we have a URL. 1141 | if (!options.url) { 1142 | params.url = _.result(model, 'url') || urlError(); 1143 | } 1144 | 1145 | // Ensure that we have the appropriate request data. 1146 | if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { 1147 | params.contentType = 'application/json'; 1148 | params.data = JSON.stringify(options.attrs || model.toJSON(options)); 1149 | } 1150 | 1151 | // For older servers, emulate JSON by encoding the request into an HTML-form. 1152 | if (options.emulateJSON) { 1153 | params.contentType = 'application/x-www-form-urlencoded'; 1154 | params.data = params.data ? {model: params.data} : {}; 1155 | } 1156 | 1157 | // For older servers, emulate HTTP by mimicking the HTTP method with `_method` 1158 | // And an `X-HTTP-Method-Override` header. 1159 | if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { 1160 | params.type = 'POST'; 1161 | if (options.emulateJSON) params.data._method = type; 1162 | var beforeSend = options.beforeSend; 1163 | options.beforeSend = function(xhr) { 1164 | xhr.setRequestHeader('X-HTTP-Method-Override', type); 1165 | if (beforeSend) return beforeSend.apply(this, arguments); 1166 | }; 1167 | } 1168 | 1169 | // Don't process data on a non-GET request. 1170 | if (params.type !== 'GET' && !options.emulateJSON) { 1171 | params.processData = false; 1172 | } 1173 | 1174 | // If we're sending a `PATCH` request, and we're in an old Internet Explorer 1175 | // that still has ActiveX enabled by default, override jQuery to use that 1176 | // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. 1177 | if (params.type === 'PATCH' && window.ActiveXObject && 1178 | !(window.external && window.external.msActiveXFilteringEnabled)) { 1179 | params.xhr = function() { 1180 | return new ActiveXObject("Microsoft.XMLHTTP"); 1181 | }; 1182 | } 1183 | 1184 | // Make the request, allowing the user to override any Ajax options. 1185 | var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); 1186 | model.trigger('request', model, xhr, options); 1187 | return xhr; 1188 | }; 1189 | 1190 | // Map from CRUD to HTTP for our default `Backbone.sync` implementation. 1191 | var methodMap = { 1192 | 'create': 'POST', 1193 | 'update': 'PUT', 1194 | 'patch': 'PATCH', 1195 | 'delete': 'DELETE', 1196 | 'read': 'GET' 1197 | }; 1198 | 1199 | // Set the default implementation of `Backbone.ajax` to proxy through to `$`. 1200 | // Override this if you'd like to use a different library. 1201 | Backbone.ajax = function() { 1202 | return Backbone.$.ajax.apply(Backbone.$, arguments); 1203 | }; 1204 | 1205 | // Backbone.Router 1206 | // --------------- 1207 | 1208 | // Routers map faux-URLs to actions, and fire events when routes are 1209 | // matched. Creating a new one sets its `routes` hash, if not set statically. 1210 | var Router = Backbone.Router = function(options) { 1211 | options || (options = {}); 1212 | if (options.routes) this.routes = options.routes; 1213 | this._bindRoutes(); 1214 | this.initialize.apply(this, arguments); 1215 | }; 1216 | 1217 | // Cached regular expressions for matching named param parts and splatted 1218 | // parts of route strings. 1219 | var optionalParam = /\((.*?)\)/g; 1220 | var namedParam = /(\(\?)?:\w+/g; 1221 | var splatParam = /\*\w+/g; 1222 | var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; 1223 | 1224 | // Set up all inheritable **Backbone.Router** properties and methods. 1225 | _.extend(Router.prototype, Events, { 1226 | 1227 | // Initialize is an empty function by default. Override it with your own 1228 | // initialization logic. 1229 | initialize: function(){}, 1230 | 1231 | // Manually bind a single named route to a callback. For example: 1232 | // 1233 | // this.route('search/:query/p:num', 'search', function(query, num) { 1234 | // ... 1235 | // }); 1236 | // 1237 | route: function(route, name, callback) { 1238 | if (!_.isRegExp(route)) route = this._routeToRegExp(route); 1239 | if (_.isFunction(name)) { 1240 | callback = name; 1241 | name = ''; 1242 | } 1243 | if (!callback) callback = this[name]; 1244 | var router = this; 1245 | Backbone.history.route(route, function(fragment) { 1246 | var args = router._extractParameters(route, fragment); 1247 | callback && callback.apply(router, args); 1248 | router.trigger.apply(router, ['route:' + name].concat(args)); 1249 | router.trigger('route', name, args); 1250 | Backbone.history.trigger('route', router, name, args); 1251 | }); 1252 | return this; 1253 | }, 1254 | 1255 | // Simple proxy to `Backbone.history` to save a fragment into the history. 1256 | navigate: function(fragment, options) { 1257 | Backbone.history.navigate(fragment, options); 1258 | return this; 1259 | }, 1260 | 1261 | // Bind all defined routes to `Backbone.history`. We have to reverse the 1262 | // order of the routes here to support behavior where the most general 1263 | // routes can be defined at the bottom of the route map. 1264 | _bindRoutes: function() { 1265 | if (!this.routes) return; 1266 | this.routes = _.result(this, 'routes'); 1267 | var route, routes = _.keys(this.routes); 1268 | while ((route = routes.pop()) != null) { 1269 | this.route(route, this.routes[route]); 1270 | } 1271 | }, 1272 | 1273 | // Convert a route string into a regular expression, suitable for matching 1274 | // against the current location hash. 1275 | _routeToRegExp: function(route) { 1276 | route = route.replace(escapeRegExp, '\\$&') 1277 | .replace(optionalParam, '(?:$1)?') 1278 | .replace(namedParam, function(match, optional){ 1279 | return optional ? match : '([^\/]+)'; 1280 | }) 1281 | .replace(splatParam, '(.*?)'); 1282 | return new RegExp('^' + route + '$'); 1283 | }, 1284 | 1285 | // Given a route, and a URL fragment that it matches, return the array of 1286 | // extracted decoded parameters. Empty or unmatched parameters will be 1287 | // treated as `null` to normalize cross-browser behavior. 1288 | _extractParameters: function(route, fragment) { 1289 | var params = route.exec(fragment).slice(1); 1290 | return _.map(params, function(param) { 1291 | return param ? decodeURIComponent(param) : null; 1292 | }); 1293 | } 1294 | 1295 | }); 1296 | 1297 | // Backbone.History 1298 | // ---------------- 1299 | 1300 | // Handles cross-browser history management, based on either 1301 | // [pushState](http://diveintohtml5.info/history.html) and real URLs, or 1302 | // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) 1303 | // and URL fragments. If the browser supports neither (old IE, natch), 1304 | // falls back to polling. 1305 | var History = Backbone.History = function() { 1306 | this.handlers = []; 1307 | _.bindAll(this, 'checkUrl'); 1308 | 1309 | // Ensure that `History` can be used outside of the browser. 1310 | if (typeof window !== 'undefined') { 1311 | this.location = window.location; 1312 | this.history = window.history; 1313 | } 1314 | }; 1315 | 1316 | // Cached regex for stripping a leading hash/slash and trailing space. 1317 | var routeStripper = /^[#\/]|\s+$/g; 1318 | 1319 | // Cached regex for stripping leading and trailing slashes. 1320 | var rootStripper = /^\/+|\/+$/g; 1321 | 1322 | // Cached regex for detecting MSIE. 1323 | var isExplorer = /msie [\w.]+/; 1324 | 1325 | // Cached regex for removing a trailing slash. 1326 | var trailingSlash = /\/$/; 1327 | 1328 | // Has the history handling already been started? 1329 | History.started = false; 1330 | 1331 | // Set up all inheritable **Backbone.History** properties and methods. 1332 | _.extend(History.prototype, Events, { 1333 | 1334 | // The default interval to poll for hash changes, if necessary, is 1335 | // twenty times a second. 1336 | interval: 50, 1337 | 1338 | // Gets the true hash value. Cannot use location.hash directly due to bug 1339 | // in Firefox where location.hash will always be decoded. 1340 | getHash: function(window) { 1341 | var match = (window || this).location.href.match(/#(.*)$/); 1342 | return match ? match[1] : ''; 1343 | }, 1344 | 1345 | // Get the cross-browser normalized URL fragment, either from the URL, 1346 | // the hash, or the override. 1347 | getFragment: function(fragment, forcePushState) { 1348 | if (fragment == null) { 1349 | if (this._hasPushState || !this._wantsHashChange || forcePushState) { 1350 | fragment = this.location.pathname; 1351 | var root = this.root.replace(trailingSlash, ''); 1352 | if (!fragment.indexOf(root)) fragment = fragment.substr(root.length); 1353 | } else { 1354 | fragment = this.getHash(); 1355 | } 1356 | } 1357 | return fragment.replace(routeStripper, ''); 1358 | }, 1359 | 1360 | // Start the hash change handling, returning `true` if the current URL matches 1361 | // an existing route, and `false` otherwise. 1362 | start: function(options) { 1363 | if (History.started) throw new Error("Backbone.history has already been started"); 1364 | History.started = true; 1365 | 1366 | // Figure out the initial configuration. Do we need an iframe? 1367 | // Is pushState desired ... is it available? 1368 | this.options = _.extend({}, {root: '/'}, this.options, options); 1369 | this.root = this.options.root; 1370 | this._wantsHashChange = this.options.hashChange !== false; 1371 | this._wantsPushState = !!this.options.pushState; 1372 | this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); 1373 | var fragment = this.getFragment(); 1374 | var docMode = document.documentMode; 1375 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); 1376 | 1377 | // Normalize root to always include a leading and trailing slash. 1378 | this.root = ('/' + this.root + '/').replace(rootStripper, '/'); 1379 | 1380 | if (oldIE && this._wantsHashChange) { 1381 | this.iframe = Backbone.$('