├── .gitignore ├── www ├── js │ ├── app │ │ ├── controller │ │ │ ├── c1.js │ │ │ ├── c2.js │ │ │ └── Base.js │ │ ├── model │ │ │ ├── m1.js │ │ │ ├── m2.js │ │ │ └── Base.js │ │ ├── lib.js │ │ ├── main2.js │ │ └── main1.js │ ├── common.js │ └── lib │ │ ├── underscore.js │ │ ├── backbone.js │ │ └── require.js ├── page1.html └── page2.html ├── package.json ├── tools └── build.js └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | www-built 2 | www-ghpages -------------------------------------------------------------------------------- /www/js/app/controller/c1.js: -------------------------------------------------------------------------------- 1 | define(['./Base'], function (Base) { 2 | var c1 = new Base('Controller 1'); 3 | return c1; 4 | }); 5 | -------------------------------------------------------------------------------- /www/js/app/controller/c2.js: -------------------------------------------------------------------------------- 1 | define(['./Base'], function (Base) { 2 | var c2 = new Base('Controller 2'); 3 | return c2; 4 | }); 5 | -------------------------------------------------------------------------------- /www/js/app/model/m1.js: -------------------------------------------------------------------------------- 1 | define(['./Base'], function (Base) { 2 | var m1 = new Base('This is the data for Page 1'); 3 | return m1; 4 | }); 5 | -------------------------------------------------------------------------------- /www/js/app/model/m2.js: -------------------------------------------------------------------------------- 1 | define(['./Base'], function (Base) { 2 | var m2 = new Base('This is the data for Page 2'); 3 | return m2; 4 | }); 5 | -------------------------------------------------------------------------------- /www/js/app/lib.js: -------------------------------------------------------------------------------- 1 | define(['jquery'], function ($) { 2 | return { 3 | getBody: function () { 4 | return $('body'); 5 | } 6 | } 7 | }); 8 | -------------------------------------------------------------------------------- /www/js/app/model/Base.js: -------------------------------------------------------------------------------- 1 | define(function () { 2 | function modelBase(title) { 3 | this.title = title; 4 | } 5 | 6 | modelBase.prototype = { 7 | getTitle: function () { 8 | return this.title; 9 | } 10 | }; 11 | 12 | return modelBase; 13 | }); 14 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "amd": {}, 3 | "volo": { 4 | "baseUrl": "www/js/lib", 5 | "dependencies": { 6 | "jquery": "github:jquery/jquery/1.8.0", 7 | "underscore": "github:documentcloud/underscore/1.3.3", 8 | "backbone": "github:documentcloud/backbone/0.9.2" 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /www/js/app/main2.js: -------------------------------------------------------------------------------- 1 | define(function (require) { 2 | var $ = require('jquery'), 3 | lib = require('./lib'), 4 | controller = require('./controller/c2'), 5 | model = require('./model/m2'); 6 | 7 | //A fabricated API to show interaction of 8 | //common and specific pieces. 9 | controller.setModel(model); 10 | $(function () { 11 | controller.render(lib.getBody()); 12 | }); 13 | }); 14 | -------------------------------------------------------------------------------- /www/js/app/controller/Base.js: -------------------------------------------------------------------------------- 1 | define(function () { 2 | function controllerBase(id) { 3 | this.id = id; 4 | } 5 | 6 | controllerBase.prototype = { 7 | setModel: function (model) { 8 | this.model = model; 9 | }, 10 | 11 | render: function (bodyDom) { 12 | bodyDom.prepend('

Controller ' + this.id + ' says "' + 13 | this.model.getTitle() + '"

'); 14 | } 15 | }; 16 | 17 | return controllerBase; 18 | }); 19 | -------------------------------------------------------------------------------- /www/js/common.js: -------------------------------------------------------------------------------- 1 | //The build will inline common dependencies into this file. 2 | 3 | //For any third party dependencies, like jQuery, place them in the lib folder. 4 | 5 | //Configure loading modules from the lib directory, 6 | //except for 'app' ones, which are in a sibling 7 | //directory. 8 | requirejs.config({ 9 | baseUrl: 'js/lib', 10 | paths: { 11 | app: '../app' 12 | }, 13 | shim: { 14 | backbone: { 15 | deps: ['jquery', 'underscore'], 16 | exports: 'Backbone' 17 | }, 18 | underscore: { 19 | exports: '_' 20 | } 21 | } 22 | }); 23 | -------------------------------------------------------------------------------- /www/js/app/main1.js: -------------------------------------------------------------------------------- 1 | define(function (require) { 2 | var $ = require('jquery'), 3 | lib = require('./lib'), 4 | controller = require('./controller/c1'), 5 | model = require('./model/m1'), 6 | backbone = require('backbone'), 7 | underscore = require('underscore'); 8 | 9 | //A fabricated API to show interaction of 10 | //common and specific pieces. 11 | controller.setModel(model); 12 | $(function () { 13 | controller.render(lib.getBody()); 14 | 15 | //Display backbone and underscore versions 16 | $('body') 17 | .append('
backbone version: ' + backbone.VERSION + '
') 18 | .append('
underscore version: ' + underscore.VERSION + '
'); 19 | }); 20 | }); 21 | -------------------------------------------------------------------------------- /www/page1.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Page 1 5 | 6 | 18 | 19 | 20 | Go to Page 2 21 | 22 | 23 | -------------------------------------------------------------------------------- /www/page2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Page 2 5 | 6 | 18 | 19 | 20 | Go to Page 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /tools/build.js: -------------------------------------------------------------------------------- 1 | { 2 | appDir: '../www', 3 | mainConfigFile: '../www/js/common.js', 4 | dir: '../www-built', 5 | modules: [ 6 | //First set up the common build layer. 7 | { 8 | //module names are relative to baseUrl 9 | name: '../common', 10 | //List common dependencies here. Only need to list 11 | //top level dependencies, "include" will find 12 | //nested dependencies. 13 | include: ['jquery', 14 | 'app/lib', 15 | 'app/controller/Base', 16 | 'app/model/Base' 17 | ] 18 | }, 19 | 20 | //Now set up a build layer for each main layer, but exclude 21 | //the common one. "exclude" will exclude nested 22 | //the nested, built dependencies from "common". Any 23 | //"exclude" that includes built modules should be 24 | //listed before the build layer that wants to exclude it. 25 | //The "page1" and "page2" modules are **not** the targets of 26 | //the optimization, because shim config is in play, and 27 | //shimmed dependencies need to maintain their load order. 28 | //In this example, common.js will hold jquery, so backbone 29 | //needs to be delayed from loading until common.js finishes. 30 | //That loading sequence is controlled in page1.js. 31 | { 32 | //module names are relative to baseUrl/paths config 33 | name: 'app/main1', 34 | exclude: ['../common'] 35 | }, 36 | 37 | { 38 | //module names are relative to baseUrl 39 | name: 'app/main2', 40 | exclude: ['../common'] 41 | } 42 | 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # requirejs/example-multipage-shim 2 | 3 | This project shows how to set up a multi-page requirejs-based project that has 4 | the following goals: 5 | 6 | * Each page uses a mix of common and page-specific modules. 7 | * All pages share the same requirejs config. 8 | * After an optimization build, the common items should be in a shared common 9 | layer, and the page-specific modules should be in a page-specific layer. 10 | * The HTML page should not have to be changed after doing the build. 11 | * **[shim config](http://requirejs.org/docs/api.html#config-shim)** is used to 12 | load Backbone and underscore. 13 | 14 | This **project is different** from the standard 15 | [requirejs/example-multipage](https://github.com/requirejs/example-multipage) 16 | because [shim config](http://requirejs.org/docs/api.html#config-shim) 17 | is used. Shimmed modules need their dependencies loaded before they are executed. 18 | It is not as robust as normal modules. Additionally, the common.js file has 19 | shim config in it. See the js/app/main1.js file for the Backbone and underscore 20 | use. 21 | 22 | Since the shim config requires dependencies to be in the page, instead of 23 | using `data-main="js/page1"` for page1.html, this example inlines the require 24 | calls in the HTML page. If data-main was used instead, then 'js/page1' could not 25 | have any dependencies inlined, and instead still rely on the 'common' and 26 | 'app/main1' build layers to hold the modules, due to the restrictions shim 27 | config places on the build. 28 | 29 | ## Getting this project template 30 | 31 | If you are using [volo](https://github.com/volojs/volo): 32 | 33 | volo create projectname requirejs/example-multipage-shim 34 | 35 | Otherwise, 36 | [download latest zipball of master](https://github.com/requirejs/example-multipage-shim/zipball/master). 37 | 38 | ## Project layout 39 | 40 | This project has the following layout: 41 | 42 | * **tools**: The requirejs optimizer, **r.js**, and the optimizer config, 43 | **build.js.** 44 | * **www**: The code that runs in the browser while in development mode. 45 | * **www-built**: Generated after an optimizer build. Contains the built code 46 | that can be deployed to the live site. 47 | 48 | This **www** has the following layout: 49 | 50 | * **page1.html**: page 1 of the app. 51 | * **page2.html**: page 2 of the app. 52 | * **js** 53 | * **app**: the directory to store app-specific modules. 54 | * **lib**: the directory to hold third party modules, like jQuery. 55 | * **common.js**: contains the requirejs config, and it will be the build 56 | target for the set of common modules. 57 | 58 | To optimize, run: 59 | 60 | node tools/r.js -o tools/build.js 61 | 62 | That build command creates an optimized version of the project in a 63 | **www-built** directory. The **js/common.js** file will contain all the common 64 | modules. **js/app/main1.js** will contain the main1-specific modules, 65 | **js/app/main2.js** will contain the main2-specific modules. 66 | 67 | This means that for page 1, after an optimization, there will be two scripts 68 | loaded: 69 | 70 | * js/common.js 71 | * js/app/main1.js 72 | 73 | ## Building up the common layer 74 | 75 | As you do builds and see in the build output that each page is including the 76 | same module, add it to common's "include" array in **tools/build.js**. 77 | 78 | It is better to add these common modules to the **tools/build.js** config 79 | instead of doing a require([]) call for them in **js/common.js**. Modules that 80 | are not explicitly required at runtime are not executed when added to common.js 81 | via the include build option. So by using **tools/build.js**, you can include 82 | common modules that may be in 2-3 pages but not all pages. For pages that do 83 | not need a particular common module, it will not be executed. If you put in a 84 | require() call for it in **js/common.js**, then it will always be executed. 85 | 86 | ## More info 87 | 88 | For more information on the optimizer: 89 | http://requirejs.org/docs/optimization.html 90 | 91 | For more information on using requirejs: 92 | http://requirejs.org/docs/api.html 93 | -------------------------------------------------------------------------------- /www/js/lib/underscore.js: -------------------------------------------------------------------------------- 1 | // Underscore.js 1.3.3 2 | // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. 3 | // Underscore is freely distributable under the MIT license. 4 | // Portions of Underscore are inspired or borrowed from Prototype, 5 | // Oliver Steele's Functional, and John Resig's Micro-Templating. 6 | // For all details and documentation: 7 | // http://documentcloud.github.com/underscore 8 | 9 | (function() { 10 | 11 | // Baseline setup 12 | // -------------- 13 | 14 | // Establish the root object, `window` in the browser, or `global` on the server. 15 | var root = this; 16 | 17 | // Save the previous value of the `_` variable. 18 | var previousUnderscore = root._; 19 | 20 | // Establish the object that gets returned to break out of a loop iteration. 21 | var breaker = {}; 22 | 23 | // Save bytes in the minified (but not gzipped) version: 24 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; 25 | 26 | // Create quick reference variables for speed access to core prototypes. 27 | var slice = ArrayProto.slice, 28 | unshift = ArrayProto.unshift, 29 | toString = ObjProto.toString, 30 | hasOwnProperty = ObjProto.hasOwnProperty; 31 | 32 | // All **ECMAScript 5** native function implementations that we hope to use 33 | // are declared here. 34 | var 35 | nativeForEach = ArrayProto.forEach, 36 | nativeMap = ArrayProto.map, 37 | nativeReduce = ArrayProto.reduce, 38 | nativeReduceRight = ArrayProto.reduceRight, 39 | nativeFilter = ArrayProto.filter, 40 | nativeEvery = ArrayProto.every, 41 | nativeSome = ArrayProto.some, 42 | nativeIndexOf = ArrayProto.indexOf, 43 | nativeLastIndexOf = ArrayProto.lastIndexOf, 44 | nativeIsArray = Array.isArray, 45 | nativeKeys = Object.keys, 46 | nativeBind = FuncProto.bind; 47 | 48 | // Create a safe reference to the Underscore object for use below. 49 | var _ = function(obj) { return new wrapper(obj); }; 50 | 51 | // Export the Underscore object for **Node.js** and **"CommonJS"**, with 52 | // backwards-compatibility for the old `require()` API. If we're not in 53 | // CommonJS, add `_` to the global object via a string identifier for 54 | // the Closure Compiler "advanced" mode. Registration as an AMD module 55 | // via define() happens at the end of this file. 56 | if (typeof exports !== 'undefined') { 57 | if (typeof module !== 'undefined' && module.exports) { 58 | exports = module.exports = _; 59 | } 60 | exports._ = _; 61 | } else { 62 | root['_'] = _; 63 | } 64 | 65 | // Current version. 66 | _.VERSION = '1.3.3'; 67 | 68 | // Collection Functions 69 | // -------------------- 70 | 71 | // The cornerstone, an `each` implementation, aka `forEach`. 72 | // Handles objects with the built-in `forEach`, arrays, and raw objects. 73 | // Delegates to **ECMAScript 5**'s native `forEach` if available. 74 | var each = _.each = _.forEach = function(obj, iterator, context) { 75 | if (obj == null) return; 76 | if (nativeForEach && obj.forEach === nativeForEach) { 77 | obj.forEach(iterator, context); 78 | } else if (obj.length === +obj.length) { 79 | for (var i = 0, l = obj.length; i < l; i++) { 80 | if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; 81 | } 82 | } else { 83 | for (var key in obj) { 84 | if (_.has(obj, key)) { 85 | if (iterator.call(context, obj[key], key, obj) === breaker) return; 86 | } 87 | } 88 | } 89 | }; 90 | 91 | // Return the results of applying the iterator to each element. 92 | // Delegates to **ECMAScript 5**'s native `map` if available. 93 | _.map = _.collect = function(obj, iterator, context) { 94 | var results = []; 95 | if (obj == null) return results; 96 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); 97 | each(obj, function(value, index, list) { 98 | results[results.length] = iterator.call(context, value, index, list); 99 | }); 100 | if (obj.length === +obj.length) results.length = obj.length; 101 | return results; 102 | }; 103 | 104 | // **Reduce** builds up a single result from a list of values, aka `inject`, 105 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. 106 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { 107 | var initial = arguments.length > 2; 108 | if (obj == null) obj = []; 109 | if (nativeReduce && obj.reduce === nativeReduce) { 110 | if (context) iterator = _.bind(iterator, context); 111 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); 112 | } 113 | each(obj, function(value, index, list) { 114 | if (!initial) { 115 | memo = value; 116 | initial = true; 117 | } else { 118 | memo = iterator.call(context, memo, value, index, list); 119 | } 120 | }); 121 | if (!initial) throw new TypeError('Reduce of empty array with no initial value'); 122 | return memo; 123 | }; 124 | 125 | // The right-associative version of reduce, also known as `foldr`. 126 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available. 127 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) { 128 | var initial = arguments.length > 2; 129 | if (obj == null) obj = []; 130 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { 131 | if (context) iterator = _.bind(iterator, context); 132 | return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); 133 | } 134 | var reversed = _.toArray(obj).reverse(); 135 | if (context && !initial) iterator = _.bind(iterator, context); 136 | return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator); 137 | }; 138 | 139 | // Return the first value which passes a truth test. Aliased as `detect`. 140 | _.find = _.detect = function(obj, iterator, context) { 141 | var result; 142 | any(obj, function(value, index, list) { 143 | if (iterator.call(context, value, index, list)) { 144 | result = value; 145 | return true; 146 | } 147 | }); 148 | return result; 149 | }; 150 | 151 | // Return all the elements that pass a truth test. 152 | // Delegates to **ECMAScript 5**'s native `filter` if available. 153 | // Aliased as `select`. 154 | _.filter = _.select = function(obj, iterator, context) { 155 | var results = []; 156 | if (obj == null) return results; 157 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); 158 | each(obj, function(value, index, list) { 159 | if (iterator.call(context, value, index, list)) results[results.length] = value; 160 | }); 161 | return results; 162 | }; 163 | 164 | // Return all the elements for which a truth test fails. 165 | _.reject = function(obj, iterator, context) { 166 | var results = []; 167 | if (obj == null) return results; 168 | each(obj, function(value, index, list) { 169 | if (!iterator.call(context, value, index, list)) results[results.length] = value; 170 | }); 171 | return results; 172 | }; 173 | 174 | // Determine whether all of the elements match a truth test. 175 | // Delegates to **ECMAScript 5**'s native `every` if available. 176 | // Aliased as `all`. 177 | _.every = _.all = function(obj, iterator, context) { 178 | var result = true; 179 | if (obj == null) return result; 180 | if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); 181 | each(obj, function(value, index, list) { 182 | if (!(result = result && iterator.call(context, value, index, list))) return breaker; 183 | }); 184 | return !!result; 185 | }; 186 | 187 | // Determine if at least one element in the object matches a truth test. 188 | // Delegates to **ECMAScript 5**'s native `some` if available. 189 | // Aliased as `any`. 190 | var any = _.some = _.any = function(obj, iterator, context) { 191 | iterator || (iterator = _.identity); 192 | var result = false; 193 | if (obj == null) return result; 194 | if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); 195 | each(obj, function(value, index, list) { 196 | if (result || (result = iterator.call(context, value, index, list))) return breaker; 197 | }); 198 | return !!result; 199 | }; 200 | 201 | // Determine if a given value is included in the array or object using `===`. 202 | // Aliased as `contains`. 203 | _.include = _.contains = function(obj, target) { 204 | var found = false; 205 | if (obj == null) return found; 206 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; 207 | found = any(obj, function(value) { 208 | return value === target; 209 | }); 210 | return found; 211 | }; 212 | 213 | // Invoke a method (with arguments) on every item in a collection. 214 | _.invoke = function(obj, method) { 215 | var args = slice.call(arguments, 2); 216 | return _.map(obj, function(value) { 217 | return (_.isFunction(method) ? method || value : value[method]).apply(value, args); 218 | }); 219 | }; 220 | 221 | // Convenience version of a common use case of `map`: fetching a property. 222 | _.pluck = function(obj, key) { 223 | return _.map(obj, function(value){ return value[key]; }); 224 | }; 225 | 226 | // Return the maximum element or (element-based computation). 227 | _.max = function(obj, iterator, context) { 228 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.max.apply(Math, obj); 229 | if (!iterator && _.isEmpty(obj)) return -Infinity; 230 | var result = {computed : -Infinity}; 231 | each(obj, function(value, index, list) { 232 | var computed = iterator ? iterator.call(context, value, index, list) : value; 233 | computed >= result.computed && (result = {value : value, computed : computed}); 234 | }); 235 | return result.value; 236 | }; 237 | 238 | // Return the minimum element (or element-based computation). 239 | _.min = function(obj, iterator, context) { 240 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.min.apply(Math, obj); 241 | if (!iterator && _.isEmpty(obj)) return Infinity; 242 | var result = {computed : Infinity}; 243 | each(obj, function(value, index, list) { 244 | var computed = iterator ? iterator.call(context, value, index, list) : value; 245 | computed < result.computed && (result = {value : value, computed : computed}); 246 | }); 247 | return result.value; 248 | }; 249 | 250 | // Shuffle an array. 251 | _.shuffle = function(obj) { 252 | var shuffled = [], rand; 253 | each(obj, function(value, index, list) { 254 | rand = Math.floor(Math.random() * (index + 1)); 255 | shuffled[index] = shuffled[rand]; 256 | shuffled[rand] = value; 257 | }); 258 | return shuffled; 259 | }; 260 | 261 | // Sort the object's values by a criterion produced by an iterator. 262 | _.sortBy = function(obj, val, context) { 263 | var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; 264 | return _.pluck(_.map(obj, function(value, index, list) { 265 | return { 266 | value : value, 267 | criteria : iterator.call(context, value, index, list) 268 | }; 269 | }).sort(function(left, right) { 270 | var a = left.criteria, b = right.criteria; 271 | if (a === void 0) return 1; 272 | if (b === void 0) return -1; 273 | return a < b ? -1 : a > b ? 1 : 0; 274 | }), 'value'); 275 | }; 276 | 277 | // Groups the object's values by a criterion. Pass either a string attribute 278 | // to group by, or a function that returns the criterion. 279 | _.groupBy = function(obj, val) { 280 | var result = {}; 281 | var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; 282 | each(obj, function(value, index) { 283 | var key = iterator(value, index); 284 | (result[key] || (result[key] = [])).push(value); 285 | }); 286 | return result; 287 | }; 288 | 289 | // Use a comparator function to figure out at what index an object should 290 | // be inserted so as to maintain order. Uses binary search. 291 | _.sortedIndex = function(array, obj, iterator) { 292 | iterator || (iterator = _.identity); 293 | var low = 0, high = array.length; 294 | while (low < high) { 295 | var mid = (low + high) >> 1; 296 | iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; 297 | } 298 | return low; 299 | }; 300 | 301 | // Safely convert anything iterable into a real, live array. 302 | _.toArray = function(obj) { 303 | if (!obj) return []; 304 | if (_.isArray(obj)) return slice.call(obj); 305 | if (_.isArguments(obj)) return slice.call(obj); 306 | if (obj.toArray && _.isFunction(obj.toArray)) return obj.toArray(); 307 | return _.values(obj); 308 | }; 309 | 310 | // Return the number of elements in an object. 311 | _.size = function(obj) { 312 | return _.isArray(obj) ? obj.length : _.keys(obj).length; 313 | }; 314 | 315 | // Array Functions 316 | // --------------- 317 | 318 | // Get the first element of an array. Passing **n** will return the first N 319 | // values in the array. Aliased as `head` and `take`. The **guard** check 320 | // allows it to work with `_.map`. 321 | _.first = _.head = _.take = function(array, n, guard) { 322 | return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; 323 | }; 324 | 325 | // Returns everything but the last entry of the array. Especcialy useful on 326 | // the arguments object. Passing **n** will return all the values in 327 | // the array, excluding the last N. The **guard** check allows it to work with 328 | // `_.map`. 329 | _.initial = function(array, n, guard) { 330 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); 331 | }; 332 | 333 | // Get the last element of an array. Passing **n** will return the last N 334 | // values in the array. The **guard** check allows it to work with `_.map`. 335 | _.last = function(array, n, guard) { 336 | if ((n != null) && !guard) { 337 | return slice.call(array, Math.max(array.length - n, 0)); 338 | } else { 339 | return array[array.length - 1]; 340 | } 341 | }; 342 | 343 | // Returns everything but the first entry of the array. Aliased as `tail`. 344 | // Especially useful on the arguments object. Passing an **index** will return 345 | // the rest of the values in the array from that index onward. The **guard** 346 | // check allows it to work with `_.map`. 347 | _.rest = _.tail = function(array, index, guard) { 348 | return slice.call(array, (index == null) || guard ? 1 : index); 349 | }; 350 | 351 | // Trim out all falsy values from an array. 352 | _.compact = function(array) { 353 | return _.filter(array, function(value){ return !!value; }); 354 | }; 355 | 356 | // Return a completely flattened version of an array. 357 | _.flatten = function(array, shallow) { 358 | return _.reduce(array, function(memo, value) { 359 | if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); 360 | memo[memo.length] = value; 361 | return memo; 362 | }, []); 363 | }; 364 | 365 | // Return a version of the array that does not contain the specified value(s). 366 | _.without = function(array) { 367 | return _.difference(array, slice.call(arguments, 1)); 368 | }; 369 | 370 | // Produce a duplicate-free version of the array. If the array has already 371 | // been sorted, you have the option of using a faster algorithm. 372 | // Aliased as `unique`. 373 | _.uniq = _.unique = function(array, isSorted, iterator) { 374 | var initial = iterator ? _.map(array, iterator) : array; 375 | var results = []; 376 | // The `isSorted` flag is irrelevant if the array only contains two elements. 377 | if (array.length < 3) isSorted = true; 378 | _.reduce(initial, function (memo, value, index) { 379 | if (isSorted ? _.last(memo) !== value || !memo.length : !_.include(memo, value)) { 380 | memo.push(value); 381 | results.push(array[index]); 382 | } 383 | return memo; 384 | }, []); 385 | return results; 386 | }; 387 | 388 | // Produce an array that contains the union: each distinct element from all of 389 | // the passed-in arrays. 390 | _.union = function() { 391 | return _.uniq(_.flatten(arguments, true)); 392 | }; 393 | 394 | // Produce an array that contains every item shared between all the 395 | // passed-in arrays. (Aliased as "intersect" for back-compat.) 396 | _.intersection = _.intersect = function(array) { 397 | var rest = slice.call(arguments, 1); 398 | return _.filter(_.uniq(array), function(item) { 399 | return _.every(rest, function(other) { 400 | return _.indexOf(other, item) >= 0; 401 | }); 402 | }); 403 | }; 404 | 405 | // Take the difference between one array and a number of other arrays. 406 | // Only the elements present in just the first array will remain. 407 | _.difference = function(array) { 408 | var rest = _.flatten(slice.call(arguments, 1), true); 409 | return _.filter(array, function(value){ return !_.include(rest, value); }); 410 | }; 411 | 412 | // Zip together multiple lists into a single array -- elements that share 413 | // an index go together. 414 | _.zip = function() { 415 | var args = slice.call(arguments); 416 | var length = _.max(_.pluck(args, 'length')); 417 | var results = new Array(length); 418 | for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); 419 | return results; 420 | }; 421 | 422 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), 423 | // we need this function. Return the position of the first occurrence of an 424 | // item in an array, or -1 if the item is not included in the array. 425 | // Delegates to **ECMAScript 5**'s native `indexOf` if available. 426 | // If the array is large and already in sort order, pass `true` 427 | // for **isSorted** to use binary search. 428 | _.indexOf = function(array, item, isSorted) { 429 | if (array == null) return -1; 430 | var i, l; 431 | if (isSorted) { 432 | i = _.sortedIndex(array, item); 433 | return array[i] === item ? i : -1; 434 | } 435 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); 436 | for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i; 437 | return -1; 438 | }; 439 | 440 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. 441 | _.lastIndexOf = function(array, item) { 442 | if (array == null) return -1; 443 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); 444 | var i = array.length; 445 | while (i--) if (i in array && array[i] === item) return i; 446 | return -1; 447 | }; 448 | 449 | // Generate an integer Array containing an arithmetic progression. A port of 450 | // the native Python `range()` function. See 451 | // [the Python documentation](http://docs.python.org/library/functions.html#range). 452 | _.range = function(start, stop, step) { 453 | if (arguments.length <= 1) { 454 | stop = start || 0; 455 | start = 0; 456 | } 457 | step = arguments[2] || 1; 458 | 459 | var len = Math.max(Math.ceil((stop - start) / step), 0); 460 | var idx = 0; 461 | var range = new Array(len); 462 | 463 | while(idx < len) { 464 | range[idx++] = start; 465 | start += step; 466 | } 467 | 468 | return range; 469 | }; 470 | 471 | // Function (ahem) Functions 472 | // ------------------ 473 | 474 | // Reusable constructor function for prototype setting. 475 | var ctor = function(){}; 476 | 477 | // Create a function bound to a given object (assigning `this`, and arguments, 478 | // optionally). Binding with arguments is also known as `curry`. 479 | // Delegates to **ECMAScript 5**'s native `Function.bind` if available. 480 | // We check for `func.bind` first, to fail fast when `func` is undefined. 481 | _.bind = function bind(func, context) { 482 | var bound, args; 483 | if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); 484 | if (!_.isFunction(func)) throw new TypeError; 485 | args = slice.call(arguments, 2); 486 | return bound = function() { 487 | if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); 488 | ctor.prototype = func.prototype; 489 | var self = new ctor; 490 | var result = func.apply(self, args.concat(slice.call(arguments))); 491 | if (Object(result) === result) return result; 492 | return self; 493 | }; 494 | }; 495 | 496 | // Bind all of an object's methods to that object. Useful for ensuring that 497 | // all callbacks defined on an object belong to it. 498 | _.bindAll = function(obj) { 499 | var funcs = slice.call(arguments, 1); 500 | if (funcs.length == 0) funcs = _.functions(obj); 501 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); 502 | return obj; 503 | }; 504 | 505 | // Memoize an expensive function by storing its results. 506 | _.memoize = function(func, hasher) { 507 | var memo = {}; 508 | hasher || (hasher = _.identity); 509 | return function() { 510 | var key = hasher.apply(this, arguments); 511 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); 512 | }; 513 | }; 514 | 515 | // Delays a function for the given number of milliseconds, and then calls 516 | // it with the arguments supplied. 517 | _.delay = function(func, wait) { 518 | var args = slice.call(arguments, 2); 519 | return setTimeout(function(){ return func.apply(null, args); }, wait); 520 | }; 521 | 522 | // Defers a function, scheduling it to run after the current call stack has 523 | // cleared. 524 | _.defer = function(func) { 525 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); 526 | }; 527 | 528 | // Returns a function, that, when invoked, will only be triggered at most once 529 | // during a given window of time. 530 | _.throttle = function(func, wait) { 531 | var context, args, timeout, throttling, more, result; 532 | var whenDone = _.debounce(function(){ more = throttling = false; }, wait); 533 | return function() { 534 | context = this; args = arguments; 535 | var later = function() { 536 | timeout = null; 537 | if (more) func.apply(context, args); 538 | whenDone(); 539 | }; 540 | if (!timeout) timeout = setTimeout(later, wait); 541 | if (throttling) { 542 | more = true; 543 | } else { 544 | result = func.apply(context, args); 545 | } 546 | whenDone(); 547 | throttling = true; 548 | return result; 549 | }; 550 | }; 551 | 552 | // Returns a function, that, as long as it continues to be invoked, will not 553 | // be triggered. The function will be called after it stops being called for 554 | // N milliseconds. If `immediate` is passed, trigger the function on the 555 | // leading edge, instead of the trailing. 556 | _.debounce = function(func, wait, immediate) { 557 | var timeout; 558 | return function() { 559 | var context = this, args = arguments; 560 | var later = function() { 561 | timeout = null; 562 | if (!immediate) func.apply(context, args); 563 | }; 564 | if (immediate && !timeout) func.apply(context, args); 565 | clearTimeout(timeout); 566 | timeout = setTimeout(later, wait); 567 | }; 568 | }; 569 | 570 | // Returns a function that will be executed at most one time, no matter how 571 | // often you call it. Useful for lazy initialization. 572 | _.once = function(func) { 573 | var ran = false, memo; 574 | return function() { 575 | if (ran) return memo; 576 | ran = true; 577 | return memo = func.apply(this, arguments); 578 | }; 579 | }; 580 | 581 | // Returns the first function passed as an argument to the second, 582 | // allowing you to adjust arguments, run code before and after, and 583 | // conditionally execute the original function. 584 | _.wrap = function(func, wrapper) { 585 | return function() { 586 | var args = [func].concat(slice.call(arguments, 0)); 587 | return wrapper.apply(this, args); 588 | }; 589 | }; 590 | 591 | // Returns a function that is the composition of a list of functions, each 592 | // consuming the return value of the function that follows. 593 | _.compose = function() { 594 | var funcs = arguments; 595 | return function() { 596 | var args = arguments; 597 | for (var i = funcs.length - 1; i >= 0; i--) { 598 | args = [funcs[i].apply(this, args)]; 599 | } 600 | return args[0]; 601 | }; 602 | }; 603 | 604 | // Returns a function that will only be executed after being called N times. 605 | _.after = function(times, func) { 606 | if (times <= 0) return func(); 607 | return function() { 608 | if (--times < 1) { return func.apply(this, arguments); } 609 | }; 610 | }; 611 | 612 | // Object Functions 613 | // ---------------- 614 | 615 | // Retrieve the names of an object's properties. 616 | // Delegates to **ECMAScript 5**'s native `Object.keys` 617 | _.keys = nativeKeys || function(obj) { 618 | if (obj !== Object(obj)) throw new TypeError('Invalid object'); 619 | var keys = []; 620 | for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; 621 | return keys; 622 | }; 623 | 624 | // Retrieve the values of an object's properties. 625 | _.values = function(obj) { 626 | return _.map(obj, _.identity); 627 | }; 628 | 629 | // Return a sorted list of the function names available on the object. 630 | // Aliased as `methods` 631 | _.functions = _.methods = function(obj) { 632 | var names = []; 633 | for (var key in obj) { 634 | if (_.isFunction(obj[key])) names.push(key); 635 | } 636 | return names.sort(); 637 | }; 638 | 639 | // Extend a given object with all the properties in passed-in object(s). 640 | _.extend = function(obj) { 641 | each(slice.call(arguments, 1), function(source) { 642 | for (var prop in source) { 643 | obj[prop] = source[prop]; 644 | } 645 | }); 646 | return obj; 647 | }; 648 | 649 | // Return a copy of the object only containing the whitelisted properties. 650 | _.pick = function(obj) { 651 | var result = {}; 652 | each(_.flatten(slice.call(arguments, 1)), function(key) { 653 | if (key in obj) result[key] = obj[key]; 654 | }); 655 | return result; 656 | }; 657 | 658 | // Fill in a given object with default properties. 659 | _.defaults = function(obj) { 660 | each(slice.call(arguments, 1), function(source) { 661 | for (var prop in source) { 662 | if (obj[prop] == null) obj[prop] = source[prop]; 663 | } 664 | }); 665 | return obj; 666 | }; 667 | 668 | // Create a (shallow-cloned) duplicate of an object. 669 | _.clone = function(obj) { 670 | if (!_.isObject(obj)) return obj; 671 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 672 | }; 673 | 674 | // Invokes interceptor with the obj, and then returns obj. 675 | // The primary purpose of this method is to "tap into" a method chain, in 676 | // order to perform operations on intermediate results within the chain. 677 | _.tap = function(obj, interceptor) { 678 | interceptor(obj); 679 | return obj; 680 | }; 681 | 682 | // Internal recursive comparison function. 683 | function eq(a, b, stack) { 684 | // Identical objects are equal. `0 === -0`, but they aren't identical. 685 | // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. 686 | if (a === b) return a !== 0 || 1 / a == 1 / b; 687 | // A strict comparison is necessary because `null == undefined`. 688 | if (a == null || b == null) return a === b; 689 | // Unwrap any wrapped objects. 690 | if (a._chain) a = a._wrapped; 691 | if (b._chain) b = b._wrapped; 692 | // Invoke a custom `isEqual` method if one is provided. 693 | if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); 694 | if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); 695 | // Compare `[[Class]]` names. 696 | var className = toString.call(a); 697 | if (className != toString.call(b)) return false; 698 | switch (className) { 699 | // Strings, numbers, dates, and booleans are compared by value. 700 | case '[object String]': 701 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 702 | // equivalent to `new String("5")`. 703 | return a == String(b); 704 | case '[object Number]': 705 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 706 | // other numeric values. 707 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); 708 | case '[object Date]': 709 | case '[object Boolean]': 710 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 711 | // millisecond representations. Note that invalid dates with millisecond representations 712 | // of `NaN` are not equivalent. 713 | return +a == +b; 714 | // RegExps are compared by their source patterns and flags. 715 | case '[object RegExp]': 716 | return a.source == b.source && 717 | a.global == b.global && 718 | a.multiline == b.multiline && 719 | a.ignoreCase == b.ignoreCase; 720 | } 721 | if (typeof a != 'object' || typeof b != 'object') return false; 722 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 723 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 724 | var length = stack.length; 725 | while (length--) { 726 | // Linear search. Performance is inversely proportional to the number of 727 | // unique nested structures. 728 | if (stack[length] == a) return true; 729 | } 730 | // Add the first object to the stack of traversed objects. 731 | stack.push(a); 732 | var size = 0, result = true; 733 | // Recursively compare objects and arrays. 734 | if (className == '[object Array]') { 735 | // Compare array lengths to determine if a deep comparison is necessary. 736 | size = a.length; 737 | result = size == b.length; 738 | if (result) { 739 | // Deep compare the contents, ignoring non-numeric properties. 740 | while (size--) { 741 | // Ensure commutative equality for sparse arrays. 742 | if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; 743 | } 744 | } 745 | } else { 746 | // Objects with different constructors are not equivalent. 747 | if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; 748 | // Deep compare objects. 749 | for (var key in a) { 750 | if (_.has(a, key)) { 751 | // Count the expected number of properties. 752 | size++; 753 | // Deep compare each member. 754 | if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break; 755 | } 756 | } 757 | // Ensure that both objects contain the same number of properties. 758 | if (result) { 759 | for (key in b) { 760 | if (_.has(b, key) && !(size--)) break; 761 | } 762 | result = !size; 763 | } 764 | } 765 | // Remove the first object from the stack of traversed objects. 766 | stack.pop(); 767 | return result; 768 | } 769 | 770 | // Perform a deep comparison to check if two objects are equal. 771 | _.isEqual = function(a, b) { 772 | return eq(a, b, []); 773 | }; 774 | 775 | // Is a given array, string, or object empty? 776 | // An "empty" object has no enumerable own-properties. 777 | _.isEmpty = function(obj) { 778 | if (obj == null) return true; 779 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; 780 | for (var key in obj) if (_.has(obj, key)) return false; 781 | return true; 782 | }; 783 | 784 | // Is a given value a DOM element? 785 | _.isElement = function(obj) { 786 | return !!(obj && obj.nodeType == 1); 787 | }; 788 | 789 | // Is a given value an array? 790 | // Delegates to ECMA5's native Array.isArray 791 | _.isArray = nativeIsArray || function(obj) { 792 | return toString.call(obj) == '[object Array]'; 793 | }; 794 | 795 | // Is a given variable an object? 796 | _.isObject = function(obj) { 797 | return obj === Object(obj); 798 | }; 799 | 800 | // Is a given variable an arguments object? 801 | _.isArguments = function(obj) { 802 | return toString.call(obj) == '[object Arguments]'; 803 | }; 804 | if (!_.isArguments(arguments)) { 805 | _.isArguments = function(obj) { 806 | return !!(obj && _.has(obj, 'callee')); 807 | }; 808 | } 809 | 810 | // Is a given value a function? 811 | _.isFunction = function(obj) { 812 | return toString.call(obj) == '[object Function]'; 813 | }; 814 | 815 | // Is a given value a string? 816 | _.isString = function(obj) { 817 | return toString.call(obj) == '[object String]'; 818 | }; 819 | 820 | // Is a given value a number? 821 | _.isNumber = function(obj) { 822 | return toString.call(obj) == '[object Number]'; 823 | }; 824 | 825 | // Is a given object a finite number? 826 | _.isFinite = function(obj) { 827 | return _.isNumber(obj) && isFinite(obj); 828 | }; 829 | 830 | // Is the given value `NaN`? 831 | _.isNaN = function(obj) { 832 | // `NaN` is the only value for which `===` is not reflexive. 833 | return obj !== obj; 834 | }; 835 | 836 | // Is a given value a boolean? 837 | _.isBoolean = function(obj) { 838 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; 839 | }; 840 | 841 | // Is a given value a date? 842 | _.isDate = function(obj) { 843 | return toString.call(obj) == '[object Date]'; 844 | }; 845 | 846 | // Is the given value a regular expression? 847 | _.isRegExp = function(obj) { 848 | return toString.call(obj) == '[object RegExp]'; 849 | }; 850 | 851 | // Is a given value equal to null? 852 | _.isNull = function(obj) { 853 | return obj === null; 854 | }; 855 | 856 | // Is a given variable undefined? 857 | _.isUndefined = function(obj) { 858 | return obj === void 0; 859 | }; 860 | 861 | // Has own property? 862 | _.has = function(obj, key) { 863 | return hasOwnProperty.call(obj, key); 864 | }; 865 | 866 | // Utility Functions 867 | // ----------------- 868 | 869 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 870 | // previous owner. Returns a reference to the Underscore object. 871 | _.noConflict = function() { 872 | root._ = previousUnderscore; 873 | return this; 874 | }; 875 | 876 | // Keep the identity function around for default iterators. 877 | _.identity = function(value) { 878 | return value; 879 | }; 880 | 881 | // Run a function **n** times. 882 | _.times = function (n, iterator, context) { 883 | for (var i = 0; i < n; i++) iterator.call(context, i); 884 | }; 885 | 886 | // Escape a string for HTML interpolation. 887 | _.escape = function(string) { 888 | return (''+string).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/'); 889 | }; 890 | 891 | // If the value of the named property is a function then invoke it; 892 | // otherwise, return it. 893 | _.result = function(object, property) { 894 | if (object == null) return null; 895 | var value = object[property]; 896 | return _.isFunction(value) ? value.call(object) : value; 897 | }; 898 | 899 | // Add your own custom functions to the Underscore object, ensuring that 900 | // they're correctly added to the OOP wrapper as well. 901 | _.mixin = function(obj) { 902 | each(_.functions(obj), function(name){ 903 | addToWrapper(name, _[name] = obj[name]); 904 | }); 905 | }; 906 | 907 | // Generate a unique integer id (unique within the entire client session). 908 | // Useful for temporary DOM ids. 909 | var idCounter = 0; 910 | _.uniqueId = function(prefix) { 911 | var id = idCounter++; 912 | return prefix ? prefix + id : id; 913 | }; 914 | 915 | // By default, Underscore uses ERB-style template delimiters, change the 916 | // following template settings to use alternative delimiters. 917 | _.templateSettings = { 918 | evaluate : /<%([\s\S]+?)%>/g, 919 | interpolate : /<%=([\s\S]+?)%>/g, 920 | escape : /<%-([\s\S]+?)%>/g 921 | }; 922 | 923 | // When customizing `templateSettings`, if you don't want to define an 924 | // interpolation, evaluation or escaping regex, we need one that is 925 | // guaranteed not to match. 926 | var noMatch = /.^/; 927 | 928 | // Certain characters need to be escaped so that they can be put into a 929 | // string literal. 930 | var escapes = { 931 | '\\': '\\', 932 | "'": "'", 933 | 'r': '\r', 934 | 'n': '\n', 935 | 't': '\t', 936 | 'u2028': '\u2028', 937 | 'u2029': '\u2029' 938 | }; 939 | 940 | for (var p in escapes) escapes[escapes[p]] = p; 941 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; 942 | var unescaper = /\\(\\|'|r|n|t|u2028|u2029)/g; 943 | 944 | // Within an interpolation, evaluation, or escaping, remove HTML escaping 945 | // that had been previously added. 946 | var unescape = function(code) { 947 | return code.replace(unescaper, function(match, escape) { 948 | return escapes[escape]; 949 | }); 950 | }; 951 | 952 | // JavaScript micro-templating, similar to John Resig's implementation. 953 | // Underscore templating handles arbitrary delimiters, preserves whitespace, 954 | // and correctly escapes quotes within interpolated code. 955 | _.template = function(text, data, settings) { 956 | settings = _.defaults(settings || {}, _.templateSettings); 957 | 958 | // Compile the template source, taking care to escape characters that 959 | // cannot be included in a string literal and then unescape them in code 960 | // blocks. 961 | var source = "__p+='" + text 962 | .replace(escaper, function(match) { 963 | return '\\' + escapes[match]; 964 | }) 965 | .replace(settings.escape || noMatch, function(match, code) { 966 | return "'+\n_.escape(" + unescape(code) + ")+\n'"; 967 | }) 968 | .replace(settings.interpolate || noMatch, function(match, code) { 969 | return "'+\n(" + unescape(code) + ")+\n'"; 970 | }) 971 | .replace(settings.evaluate || noMatch, function(match, code) { 972 | return "';\n" + unescape(code) + "\n;__p+='"; 973 | }) + "';\n"; 974 | 975 | // If a variable is not specified, place data values in local scope. 976 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; 977 | 978 | source = "var __p='';" + 979 | "var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n" + 980 | source + "return __p;\n"; 981 | 982 | var render = new Function(settings.variable || 'obj', '_', source); 983 | if (data) return render(data, _); 984 | var template = function(data) { 985 | return render.call(this, data, _); 986 | }; 987 | 988 | // Provide the compiled function source as a convenience for build time 989 | // precompilation. 990 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + 991 | source + '}'; 992 | 993 | return template; 994 | }; 995 | 996 | // Add a "chain" function, which will delegate to the wrapper. 997 | _.chain = function(obj) { 998 | return _(obj).chain(); 999 | }; 1000 | 1001 | // The OOP Wrapper 1002 | // --------------- 1003 | 1004 | // If Underscore is called as a function, it returns a wrapped object that 1005 | // can be used OO-style. This wrapper holds altered versions of all the 1006 | // underscore functions. Wrapped objects may be chained. 1007 | var wrapper = function(obj) { this._wrapped = obj; }; 1008 | 1009 | // Expose `wrapper.prototype` as `_.prototype` 1010 | _.prototype = wrapper.prototype; 1011 | 1012 | // Helper function to continue chaining intermediate results. 1013 | var result = function(obj, chain) { 1014 | return chain ? _(obj).chain() : obj; 1015 | }; 1016 | 1017 | // A method to easily add functions to the OOP wrapper. 1018 | var addToWrapper = function(name, func) { 1019 | wrapper.prototype[name] = function() { 1020 | var args = slice.call(arguments); 1021 | unshift.call(args, this._wrapped); 1022 | return result(func.apply(_, args), this._chain); 1023 | }; 1024 | }; 1025 | 1026 | // Add all of the Underscore functions to the wrapper object. 1027 | _.mixin(_); 1028 | 1029 | // Add all mutator Array functions to the wrapper. 1030 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 1031 | var method = ArrayProto[name]; 1032 | wrapper.prototype[name] = function() { 1033 | var wrapped = this._wrapped; 1034 | method.apply(wrapped, arguments); 1035 | var length = wrapped.length; 1036 | if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0]; 1037 | return result(wrapped, this._chain); 1038 | }; 1039 | }); 1040 | 1041 | // Add all accessor Array functions to the wrapper. 1042 | each(['concat', 'join', 'slice'], function(name) { 1043 | var method = ArrayProto[name]; 1044 | wrapper.prototype[name] = function() { 1045 | return result(method.apply(this._wrapped, arguments), this._chain); 1046 | }; 1047 | }); 1048 | 1049 | // Start chaining a wrapped Underscore object. 1050 | wrapper.prototype.chain = function() { 1051 | this._chain = true; 1052 | return this; 1053 | }; 1054 | 1055 | // Extracts the result from a wrapped and chained object. 1056 | wrapper.prototype.value = function() { 1057 | return this._wrapped; 1058 | }; 1059 | 1060 | // AMD define happens at the end for compatibility with AMD loaders 1061 | // that don't enforce next-turn semantics on modules. 1062 | if (typeof define === 'function' && define.amd) { 1063 | define('underscore', function() { 1064 | return _; 1065 | }); 1066 | } 1067 | 1068 | }).call(this); 1069 | -------------------------------------------------------------------------------- /www/js/lib/backbone.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 0.9.2 2 | 3 | // (c) 2010-2012 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, `global` 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 a local reference to slice/splice. 22 | var slice = Array.prototype.slice; 23 | var splice = Array.prototype.splice; 24 | 25 | // The top-level namespace. All public Backbone classes and modules will 26 | // be attached to this. Exported for both CommonJS and the browser. 27 | var Backbone; 28 | if (typeof exports !== 'undefined') { 29 | Backbone = exports; 30 | } else { 31 | Backbone = root.Backbone = {}; 32 | } 33 | 34 | // Current version of the library. Keep in sync with `package.json`. 35 | Backbone.VERSION = '0.9.2'; 36 | 37 | // Require Underscore, if we're on the server, and it's not already present. 38 | var _ = root._; 39 | if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); 40 | 41 | // For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable. 42 | var $ = root.jQuery || root.Zepto || root.ender; 43 | 44 | // Set the JavaScript library that will be used for DOM manipulation and 45 | // Ajax calls (a.k.a. the `$` variable). By default Backbone will use: jQuery, 46 | // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an 47 | // alternate JavaScript library (or a mock library for testing your views 48 | // outside of a browser). 49 | Backbone.setDomLibrary = function(lib) { 50 | $ = lib; 51 | }; 52 | 53 | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable 54 | // to its previous owner. Returns a reference to this Backbone object. 55 | Backbone.noConflict = function() { 56 | root.Backbone = previousBackbone; 57 | return this; 58 | }; 59 | 60 | // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option 61 | // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and 62 | // set a `X-Http-Method-Override` header. 63 | Backbone.emulateHTTP = false; 64 | 65 | // Turn on `emulateJSON` to support legacy servers that can't deal with direct 66 | // `application/json` requests ... will encode the body as 67 | // `application/x-www-form-urlencoded` instead and will send the model in a 68 | // form param named `model`. 69 | Backbone.emulateJSON = false; 70 | 71 | // Backbone.Events 72 | // ----------------- 73 | 74 | // Regular expression used to split event strings 75 | var eventSplitter = /\s+/; 76 | 77 | // A module that can be mixed in to *any object* in order to provide it with 78 | // custom events. You may bind with `on` or remove with `off` callback functions 79 | // to an event; trigger`-ing an event fires all callbacks in succession. 80 | // 81 | // var object = {}; 82 | // _.extend(object, Backbone.Events); 83 | // object.on('expand', function(){ alert('expanded'); }); 84 | // object.trigger('expand'); 85 | // 86 | var Events = Backbone.Events = { 87 | 88 | // Bind one or more space separated events, `events`, to a `callback` 89 | // function. Passing `"all"` will bind the callback to all events fired. 90 | on: function(events, callback, context) { 91 | 92 | var calls, event, node, tail, list; 93 | if (!callback) return this; 94 | events = events.split(eventSplitter); 95 | calls = this._callbacks || (this._callbacks = {}); 96 | 97 | // Create an immutable callback list, allowing traversal during 98 | // modification. The tail is an empty object that will always be used 99 | // as the next node. 100 | while (event = events.shift()) { 101 | list = calls[event]; 102 | node = list ? list.tail : {}; 103 | node.next = tail = {}; 104 | node.context = context; 105 | node.callback = callback; 106 | calls[event] = {tail: tail, next: list ? list.next : node}; 107 | } 108 | 109 | return this; 110 | }, 111 | 112 | // Remove one or many callbacks. If `context` is null, removes all callbacks 113 | // with that function. If `callback` is null, removes all callbacks for the 114 | // event. If `events` is null, removes all bound callbacks for all events. 115 | off: function(events, callback, context) { 116 | var event, calls, node, tail, cb, ctx; 117 | 118 | // No events, or removing *all* events. 119 | if (!(calls = this._callbacks)) return; 120 | if (!(events || callback || context)) { 121 | delete this._callbacks; 122 | return this; 123 | } 124 | 125 | // Loop through the listed events and contexts, splicing them out of the 126 | // linked list of callbacks if appropriate. 127 | events = events ? events.split(eventSplitter) : _.keys(calls); 128 | while (event = events.shift()) { 129 | node = calls[event]; 130 | delete calls[event]; 131 | if (!node || !(callback || context)) continue; 132 | // Create a new list, omitting the indicated callbacks. 133 | tail = node.tail; 134 | while ((node = node.next) !== tail) { 135 | cb = node.callback; 136 | ctx = node.context; 137 | if ((callback && cb !== callback) || (context && ctx !== context)) { 138 | this.on(event, cb, ctx); 139 | } 140 | } 141 | } 142 | 143 | return this; 144 | }, 145 | 146 | // Trigger one or many events, firing all bound callbacks. Callbacks are 147 | // passed the same arguments as `trigger` is, apart from the event name 148 | // (unless you're listening on `"all"`, which will cause your callback to 149 | // receive the true name of the event as the first argument). 150 | trigger: function(events) { 151 | var event, node, calls, tail, args, all, rest; 152 | if (!(calls = this._callbacks)) return this; 153 | all = calls.all; 154 | events = events.split(eventSplitter); 155 | rest = slice.call(arguments, 1); 156 | 157 | // For each event, walk through the linked list of callbacks twice, 158 | // first to trigger the event, then to trigger any `"all"` callbacks. 159 | while (event = events.shift()) { 160 | if (node = calls[event]) { 161 | tail = node.tail; 162 | while ((node = node.next) !== tail) { 163 | node.callback.apply(node.context || this, rest); 164 | } 165 | } 166 | if (node = all) { 167 | tail = node.tail; 168 | args = [event].concat(rest); 169 | while ((node = node.next) !== tail) { 170 | node.callback.apply(node.context || this, args); 171 | } 172 | } 173 | } 174 | 175 | return this; 176 | } 177 | 178 | }; 179 | 180 | // Aliases for backwards compatibility. 181 | Events.bind = Events.on; 182 | Events.unbind = Events.off; 183 | 184 | // Backbone.Model 185 | // -------------- 186 | 187 | // Create a new model, with defined attributes. A client id (`cid`) 188 | // is automatically generated and assigned for you. 189 | var Model = Backbone.Model = function(attributes, options) { 190 | var defaults; 191 | attributes || (attributes = {}); 192 | if (options && options.parse) attributes = this.parse(attributes); 193 | if (defaults = getValue(this, 'defaults')) { 194 | attributes = _.extend({}, defaults, attributes); 195 | } 196 | if (options && options.collection) this.collection = options.collection; 197 | this.attributes = {}; 198 | this._escapedAttributes = {}; 199 | this.cid = _.uniqueId('c'); 200 | this.changed = {}; 201 | this._silent = {}; 202 | this._pending = {}; 203 | this.set(attributes, {silent: true}); 204 | // Reset change tracking. 205 | this.changed = {}; 206 | this._silent = {}; 207 | this._pending = {}; 208 | this._previousAttributes = _.clone(this.attributes); 209 | this.initialize.apply(this, arguments); 210 | }; 211 | 212 | // Attach all inheritable methods to the Model prototype. 213 | _.extend(Model.prototype, Events, { 214 | 215 | // A hash of attributes whose current and previous value differ. 216 | changed: null, 217 | 218 | // A hash of attributes that have silently changed since the last time 219 | // `change` was called. Will become pending attributes on the next call. 220 | _silent: null, 221 | 222 | // A hash of attributes that have changed since the last `'change'` event 223 | // began. 224 | _pending: null, 225 | 226 | // The default name for the JSON `id` attribute is `"id"`. MongoDB and 227 | // CouchDB users may want to set this to `"_id"`. 228 | idAttribute: 'id', 229 | 230 | // Initialize is an empty function by default. Override it with your own 231 | // initialization logic. 232 | initialize: function(){}, 233 | 234 | // Return a copy of the model's `attributes` object. 235 | toJSON: function(options) { 236 | return _.clone(this.attributes); 237 | }, 238 | 239 | // Get the value of an attribute. 240 | get: function(attr) { 241 | return this.attributes[attr]; 242 | }, 243 | 244 | // Get the HTML-escaped value of an attribute. 245 | escape: function(attr) { 246 | var html; 247 | if (html = this._escapedAttributes[attr]) return html; 248 | var val = this.get(attr); 249 | return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val); 250 | }, 251 | 252 | // Returns `true` if the attribute contains a value that is not null 253 | // or undefined. 254 | has: function(attr) { 255 | return this.get(attr) != null; 256 | }, 257 | 258 | // Set a hash of model attributes on the object, firing `"change"` unless 259 | // you choose to silence it. 260 | set: function(key, value, options) { 261 | var attrs, attr, val; 262 | 263 | // Handle both 264 | if (_.isObject(key) || key == null) { 265 | attrs = key; 266 | options = value; 267 | } else { 268 | attrs = {}; 269 | attrs[key] = value; 270 | } 271 | 272 | // Extract attributes and options. 273 | options || (options = {}); 274 | if (!attrs) return this; 275 | if (attrs instanceof Model) attrs = attrs.attributes; 276 | if (options.unset) for (attr in attrs) attrs[attr] = void 0; 277 | 278 | // Run validation. 279 | if (!this._validate(attrs, options)) return false; 280 | 281 | // Check for changes of `id`. 282 | if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; 283 | 284 | var changes = options.changes = {}; 285 | var now = this.attributes; 286 | var escaped = this._escapedAttributes; 287 | var prev = this._previousAttributes || {}; 288 | 289 | // For each `set` attribute... 290 | for (attr in attrs) { 291 | val = attrs[attr]; 292 | 293 | // If the new and current value differ, record the change. 294 | if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) { 295 | delete escaped[attr]; 296 | (options.silent ? this._silent : changes)[attr] = true; 297 | } 298 | 299 | // Update or delete the current value. 300 | options.unset ? delete now[attr] : now[attr] = val; 301 | 302 | // If the new and previous value differ, record the change. If not, 303 | // then remove changes for this attribute. 304 | if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) { 305 | this.changed[attr] = val; 306 | if (!options.silent) this._pending[attr] = true; 307 | } else { 308 | delete this.changed[attr]; 309 | delete this._pending[attr]; 310 | } 311 | } 312 | 313 | // Fire the `"change"` events. 314 | if (!options.silent) this.change(options); 315 | return this; 316 | }, 317 | 318 | // Remove an attribute from the model, firing `"change"` unless you choose 319 | // to silence it. `unset` is a noop if the attribute doesn't exist. 320 | unset: function(attr, options) { 321 | (options || (options = {})).unset = true; 322 | return this.set(attr, null, options); 323 | }, 324 | 325 | // Clear all attributes on the model, firing `"change"` unless you choose 326 | // to silence it. 327 | clear: function(options) { 328 | (options || (options = {})).unset = true; 329 | return this.set(_.clone(this.attributes), options); 330 | }, 331 | 332 | // Fetch the model from the server. If the server's representation of the 333 | // model differs from its current attributes, they will be overriden, 334 | // triggering a `"change"` event. 335 | fetch: function(options) { 336 | options = options ? _.clone(options) : {}; 337 | var model = this; 338 | var success = options.success; 339 | options.success = function(resp, status, xhr) { 340 | if (!model.set(model.parse(resp, xhr), options)) return false; 341 | if (success) success(model, resp); 342 | }; 343 | options.error = Backbone.wrapError(options.error, model, options); 344 | return (this.sync || Backbone.sync).call(this, 'read', this, options); 345 | }, 346 | 347 | // Set a hash of model attributes, and sync the model to the server. 348 | // If the server returns an attributes hash that differs, the model's 349 | // state will be `set` again. 350 | save: function(key, value, options) { 351 | var attrs, current; 352 | 353 | // Handle both `("key", value)` and `({key: value})` -style calls. 354 | if (_.isObject(key) || key == null) { 355 | attrs = key; 356 | options = value; 357 | } else { 358 | attrs = {}; 359 | attrs[key] = value; 360 | } 361 | options = options ? _.clone(options) : {}; 362 | 363 | // If we're "wait"-ing to set changed attributes, validate early. 364 | if (options.wait) { 365 | if (!this._validate(attrs, options)) return false; 366 | current = _.clone(this.attributes); 367 | } 368 | 369 | // Regular saves `set` attributes before persisting to the server. 370 | var silentOptions = _.extend({}, options, {silent: true}); 371 | if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) { 372 | return false; 373 | } 374 | 375 | // After a successful server-side save, the client is (optionally) 376 | // updated with the server-side state. 377 | var model = this; 378 | var success = options.success; 379 | options.success = function(resp, status, xhr) { 380 | var serverAttrs = model.parse(resp, xhr); 381 | if (options.wait) { 382 | delete options.wait; 383 | serverAttrs = _.extend(attrs || {}, serverAttrs); 384 | } 385 | if (!model.set(serverAttrs, options)) return false; 386 | if (success) { 387 | success(model, resp); 388 | } else { 389 | model.trigger('sync', model, resp, options); 390 | } 391 | }; 392 | 393 | // Finish configuring and sending the Ajax request. 394 | options.error = Backbone.wrapError(options.error, model, options); 395 | var method = this.isNew() ? 'create' : 'update'; 396 | var xhr = (this.sync || Backbone.sync).call(this, method, this, options); 397 | if (options.wait) this.set(current, silentOptions); 398 | return xhr; 399 | }, 400 | 401 | // Destroy this model on the server if it was already persisted. 402 | // Optimistically removes the model from its collection, if it has one. 403 | // If `wait: true` is passed, waits for the server to respond before removal. 404 | destroy: function(options) { 405 | options = options ? _.clone(options) : {}; 406 | var model = this; 407 | var success = options.success; 408 | 409 | var triggerDestroy = function() { 410 | model.trigger('destroy', model, model.collection, options); 411 | }; 412 | 413 | if (this.isNew()) { 414 | triggerDestroy(); 415 | return false; 416 | } 417 | 418 | options.success = function(resp) { 419 | if (options.wait) triggerDestroy(); 420 | if (success) { 421 | success(model, resp); 422 | } else { 423 | model.trigger('sync', model, resp, options); 424 | } 425 | }; 426 | 427 | options.error = Backbone.wrapError(options.error, model, options); 428 | var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options); 429 | if (!options.wait) triggerDestroy(); 430 | return xhr; 431 | }, 432 | 433 | // Default URL for the model's representation on the server -- if you're 434 | // using Backbone's restful methods, override this to change the endpoint 435 | // that will be called. 436 | url: function() { 437 | var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError(); 438 | if (this.isNew()) return base; 439 | return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); 440 | }, 441 | 442 | // **parse** converts a response into the hash of attributes to be `set` on 443 | // the model. The default implementation is just to pass the response along. 444 | parse: function(resp, xhr) { 445 | return resp; 446 | }, 447 | 448 | // Create a new model with identical attributes to this one. 449 | clone: function() { 450 | return new this.constructor(this.attributes); 451 | }, 452 | 453 | // A model is new if it has never been saved to the server, and lacks an id. 454 | isNew: function() { 455 | return this.id == null; 456 | }, 457 | 458 | // Call this method to manually fire a `"change"` event for this model and 459 | // a `"change:attribute"` event for each changed attribute. 460 | // Calling this will cause all objects observing the model to update. 461 | change: function(options) { 462 | options || (options = {}); 463 | var changing = this._changing; 464 | this._changing = true; 465 | 466 | // Silent changes become pending changes. 467 | for (var attr in this._silent) this._pending[attr] = true; 468 | 469 | // Silent changes are triggered. 470 | var changes = _.extend({}, options.changes, this._silent); 471 | this._silent = {}; 472 | for (var attr in changes) { 473 | this.trigger('change:' + attr, this, this.get(attr), options); 474 | } 475 | if (changing) return this; 476 | 477 | // Continue firing `"change"` events while there are pending changes. 478 | while (!_.isEmpty(this._pending)) { 479 | this._pending = {}; 480 | this.trigger('change', this, options); 481 | // Pending and silent changes still remain. 482 | for (var attr in this.changed) { 483 | if (this._pending[attr] || this._silent[attr]) continue; 484 | delete this.changed[attr]; 485 | } 486 | this._previousAttributes = _.clone(this.attributes); 487 | } 488 | 489 | this._changing = false; 490 | return this; 491 | }, 492 | 493 | // Determine if the model has changed since the last `"change"` event. 494 | // If you specify an attribute name, determine if that attribute has changed. 495 | hasChanged: function(attr) { 496 | if (!arguments.length) return !_.isEmpty(this.changed); 497 | return _.has(this.changed, attr); 498 | }, 499 | 500 | // Return an object containing all the attributes that have changed, or 501 | // false if there are no changed attributes. Useful for determining what 502 | // parts of a view need to be updated and/or what attributes need to be 503 | // persisted to the server. Unset attributes will be set to undefined. 504 | // You can also pass an attributes object to diff against the model, 505 | // determining if there *would be* a change. 506 | changedAttributes: function(diff) { 507 | if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; 508 | var val, changed = false, old = this._previousAttributes; 509 | for (var attr in diff) { 510 | if (_.isEqual(old[attr], (val = diff[attr]))) continue; 511 | (changed || (changed = {}))[attr] = val; 512 | } 513 | return changed; 514 | }, 515 | 516 | // Get the previous value of an attribute, recorded at the time the last 517 | // `"change"` event was fired. 518 | previous: function(attr) { 519 | if (!arguments.length || !this._previousAttributes) return null; 520 | return this._previousAttributes[attr]; 521 | }, 522 | 523 | // Get all of the attributes of the model at the time of the previous 524 | // `"change"` event. 525 | previousAttributes: function() { 526 | return _.clone(this._previousAttributes); 527 | }, 528 | 529 | // Check if the model is currently in a valid state. It's only possible to 530 | // get into an *invalid* state if you're using silent changes. 531 | isValid: function() { 532 | return !this.validate(this.attributes); 533 | }, 534 | 535 | // Run validation against the next complete set of model attributes, 536 | // returning `true` if all is well. If a specific `error` callback has 537 | // been passed, call that instead of firing the general `"error"` event. 538 | _validate: function(attrs, options) { 539 | if (options.silent || !this.validate) return true; 540 | attrs = _.extend({}, this.attributes, attrs); 541 | var error = this.validate(attrs, options); 542 | if (!error) return true; 543 | if (options && options.error) { 544 | options.error(this, error, options); 545 | } else { 546 | this.trigger('error', this, error, options); 547 | } 548 | return false; 549 | } 550 | 551 | }); 552 | 553 | // Backbone.Collection 554 | // ------------------- 555 | 556 | // Provides a standard collection class for our sets of models, ordered 557 | // or unordered. If a `comparator` is specified, the Collection will maintain 558 | // its models in sort order, as they're added and removed. 559 | var Collection = Backbone.Collection = function(models, options) { 560 | options || (options = {}); 561 | if (options.model) this.model = options.model; 562 | if (options.comparator) this.comparator = options.comparator; 563 | this._reset(); 564 | this.initialize.apply(this, arguments); 565 | if (models) this.reset(models, {silent: true, parse: options.parse}); 566 | }; 567 | 568 | // Define the Collection's inheritable methods. 569 | _.extend(Collection.prototype, Events, { 570 | 571 | // The default model for a collection is just a **Backbone.Model**. 572 | // This should be overridden in most cases. 573 | model: Model, 574 | 575 | // Initialize is an empty function by default. Override it with your own 576 | // initialization logic. 577 | initialize: function(){}, 578 | 579 | // The JSON representation of a Collection is an array of the 580 | // models' attributes. 581 | toJSON: function(options) { 582 | return this.map(function(model){ return model.toJSON(options); }); 583 | }, 584 | 585 | // Add a model, or list of models to the set. Pass **silent** to avoid 586 | // firing the `add` event for every new model. 587 | add: function(models, options) { 588 | var i, index, length, model, cid, id, cids = {}, ids = {}, dups = []; 589 | options || (options = {}); 590 | models = _.isArray(models) ? models.slice() : [models]; 591 | 592 | // Begin by turning bare objects into model references, and preventing 593 | // invalid models or duplicate models from being added. 594 | for (i = 0, length = models.length; i < length; i++) { 595 | if (!(model = models[i] = this._prepareModel(models[i], options))) { 596 | throw new Error("Can't add an invalid model to a collection"); 597 | } 598 | cid = model.cid; 599 | id = model.id; 600 | if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) { 601 | dups.push(i); 602 | continue; 603 | } 604 | cids[cid] = ids[id] = model; 605 | } 606 | 607 | // Remove duplicates. 608 | i = dups.length; 609 | while (i--) { 610 | models.splice(dups[i], 1); 611 | } 612 | 613 | // Listen to added models' events, and index models for lookup by 614 | // `id` and by `cid`. 615 | for (i = 0, length = models.length; i < length; i++) { 616 | (model = models[i]).on('all', this._onModelEvent, this); 617 | this._byCid[model.cid] = model; 618 | if (model.id != null) this._byId[model.id] = model; 619 | } 620 | 621 | // Insert models into the collection, re-sorting if needed, and triggering 622 | // `add` events unless silenced. 623 | this.length += length; 624 | index = options.at != null ? options.at : this.models.length; 625 | splice.apply(this.models, [index, 0].concat(models)); 626 | if (this.comparator) this.sort({silent: true}); 627 | if (options.silent) return this; 628 | for (i = 0, length = this.models.length; i < length; i++) { 629 | if (!cids[(model = this.models[i]).cid]) continue; 630 | options.index = i; 631 | model.trigger('add', model, this, options); 632 | } 633 | return this; 634 | }, 635 | 636 | // Remove a model, or a list of models from the set. Pass silent to avoid 637 | // firing the `remove` event for every model removed. 638 | remove: function(models, options) { 639 | var i, l, index, model; 640 | options || (options = {}); 641 | models = _.isArray(models) ? models.slice() : [models]; 642 | for (i = 0, l = models.length; i < l; i++) { 643 | model = this.getByCid(models[i]) || this.get(models[i]); 644 | if (!model) continue; 645 | delete this._byId[model.id]; 646 | delete this._byCid[model.cid]; 647 | index = this.indexOf(model); 648 | this.models.splice(index, 1); 649 | this.length--; 650 | if (!options.silent) { 651 | options.index = index; 652 | model.trigger('remove', model, this, options); 653 | } 654 | this._removeReference(model); 655 | } 656 | return this; 657 | }, 658 | 659 | // Add a model to the end of the collection. 660 | push: function(model, options) { 661 | model = this._prepareModel(model, options); 662 | this.add(model, options); 663 | return model; 664 | }, 665 | 666 | // Remove a model from the end of the collection. 667 | pop: function(options) { 668 | var model = this.at(this.length - 1); 669 | this.remove(model, options); 670 | return model; 671 | }, 672 | 673 | // Add a model to the beginning of the collection. 674 | unshift: function(model, options) { 675 | model = this._prepareModel(model, options); 676 | this.add(model, _.extend({at: 0}, options)); 677 | return model; 678 | }, 679 | 680 | // Remove a model from the beginning of the collection. 681 | shift: function(options) { 682 | var model = this.at(0); 683 | this.remove(model, options); 684 | return model; 685 | }, 686 | 687 | // Get a model from the set by id. 688 | get: function(id) { 689 | if (id == null) return void 0; 690 | return this._byId[id.id != null ? id.id : id]; 691 | }, 692 | 693 | // Get a model from the set by client id. 694 | getByCid: function(cid) { 695 | return cid && this._byCid[cid.cid || cid]; 696 | }, 697 | 698 | // Get the model at the given index. 699 | at: function(index) { 700 | return this.models[index]; 701 | }, 702 | 703 | // Return models with matching attributes. Useful for simple cases of `filter`. 704 | where: function(attrs) { 705 | if (_.isEmpty(attrs)) return []; 706 | return this.filter(function(model) { 707 | for (var key in attrs) { 708 | if (attrs[key] !== model.get(key)) return false; 709 | } 710 | return true; 711 | }); 712 | }, 713 | 714 | // Force the collection to re-sort itself. You don't need to call this under 715 | // normal circumstances, as the set will maintain sort order as each item 716 | // is added. 717 | sort: function(options) { 718 | options || (options = {}); 719 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); 720 | var boundComparator = _.bind(this.comparator, this); 721 | if (this.comparator.length == 1) { 722 | this.models = this.sortBy(boundComparator); 723 | } else { 724 | this.models.sort(boundComparator); 725 | } 726 | if (!options.silent) this.trigger('reset', this, options); 727 | return this; 728 | }, 729 | 730 | // Pluck an attribute from each model in the collection. 731 | pluck: function(attr) { 732 | return _.map(this.models, function(model){ return model.get(attr); }); 733 | }, 734 | 735 | // When you have more items than you want to add or remove individually, 736 | // you can reset the entire set with a new list of models, without firing 737 | // any `add` or `remove` events. Fires `reset` when finished. 738 | reset: function(models, options) { 739 | models || (models = []); 740 | options || (options = {}); 741 | for (var i = 0, l = this.models.length; i < l; i++) { 742 | this._removeReference(this.models[i]); 743 | } 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 | // Fetch the default set of models for this collection, resetting the 751 | // collection when they arrive. If `add: true` is passed, appends the 752 | // models to the collection instead of resetting. 753 | fetch: function(options) { 754 | options = options ? _.clone(options) : {}; 755 | if (options.parse === undefined) options.parse = true; 756 | var collection = this; 757 | var success = options.success; 758 | options.success = function(resp, status, xhr) { 759 | collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); 760 | if (success) success(collection, resp); 761 | }; 762 | options.error = Backbone.wrapError(options.error, collection, options); 763 | return (this.sync || Backbone.sync).call(this, 'read', this, options); 764 | }, 765 | 766 | // Create a new instance of a model in this collection. Add the model to the 767 | // collection immediately, unless `wait: true` is passed, in which case we 768 | // wait for the server to agree. 769 | create: function(model, options) { 770 | var coll = this; 771 | options = options ? _.clone(options) : {}; 772 | model = this._prepareModel(model, options); 773 | if (!model) return false; 774 | if (!options.wait) coll.add(model, options); 775 | var success = options.success; 776 | options.success = function(nextModel, resp, xhr) { 777 | if (options.wait) coll.add(nextModel, options); 778 | if (success) { 779 | success(nextModel, resp); 780 | } else { 781 | nextModel.trigger('sync', model, resp, options); 782 | } 783 | }; 784 | model.save(null, options); 785 | return model; 786 | }, 787 | 788 | // **parse** converts a response into a list of models to be added to the 789 | // collection. The default implementation is just to pass it through. 790 | parse: function(resp, xhr) { 791 | return resp; 792 | }, 793 | 794 | // Proxy to _'s chain. Can't be proxied the same way the rest of the 795 | // underscore methods are proxied because it relies on the underscore 796 | // constructor. 797 | chain: function () { 798 | return _(this.models).chain(); 799 | }, 800 | 801 | // Reset all internal state. Called when the collection is reset. 802 | _reset: function(options) { 803 | this.length = 0; 804 | this.models = []; 805 | this._byId = {}; 806 | this._byCid = {}; 807 | }, 808 | 809 | // Prepare a model or hash of attributes to be added to this collection. 810 | _prepareModel: function(model, options) { 811 | options || (options = {}); 812 | if (!(model instanceof Model)) { 813 | var attrs = model; 814 | options.collection = this; 815 | model = new this.model(attrs, options); 816 | if (!model._validate(model.attributes, options)) model = false; 817 | } else if (!model.collection) { 818 | model.collection = this; 819 | } 820 | return model; 821 | }, 822 | 823 | // Internal method to remove a model's ties to a collection. 824 | _removeReference: function(model) { 825 | if (this == model.collection) { 826 | delete model.collection; 827 | } 828 | model.off('all', this._onModelEvent, this); 829 | }, 830 | 831 | // Internal method called every time a model in the set fires an event. 832 | // Sets need to update their indexes when models change ids. All other 833 | // events simply proxy through. "add" and "remove" events that originate 834 | // in other collections are ignored. 835 | _onModelEvent: function(event, model, collection, options) { 836 | if ((event == 'add' || event == 'remove') && collection != this) return; 837 | if (event == 'destroy') { 838 | this.remove(model, options); 839 | } 840 | if (model && event === 'change:' + model.idAttribute) { 841 | delete this._byId[model.previous(model.idAttribute)]; 842 | this._byId[model.id] = model; 843 | } 844 | this.trigger.apply(this, arguments); 845 | } 846 | 847 | }); 848 | 849 | // Underscore methods that we want to implement on the Collection. 850 | var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 851 | 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 852 | 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 853 | 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', 854 | 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy']; 855 | 856 | // Mix in each Underscore method as a proxy to `Collection#models`. 857 | _.each(methods, function(method) { 858 | Collection.prototype[method] = function() { 859 | return _[method].apply(_, [this.models].concat(_.toArray(arguments))); 860 | }; 861 | }); 862 | 863 | // Backbone.Router 864 | // ------------------- 865 | 866 | // Routers map faux-URLs to actions, and fire events when routes are 867 | // matched. Creating a new one sets its `routes` hash, if not set statically. 868 | var Router = Backbone.Router = function(options) { 869 | options || (options = {}); 870 | if (options.routes) this.routes = options.routes; 871 | this._bindRoutes(); 872 | this.initialize.apply(this, arguments); 873 | }; 874 | 875 | // Cached regular expressions for matching named param parts and splatted 876 | // parts of route strings. 877 | var namedParam = /:\w+/g; 878 | var splatParam = /\*\w+/g; 879 | var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; 880 | 881 | // Set up all inheritable **Backbone.Router** properties and methods. 882 | _.extend(Router.prototype, Events, { 883 | 884 | // Initialize is an empty function by default. Override it with your own 885 | // initialization logic. 886 | initialize: function(){}, 887 | 888 | // Manually bind a single named route to a callback. For example: 889 | // 890 | // this.route('search/:query/p:num', 'search', function(query, num) { 891 | // ... 892 | // }); 893 | // 894 | route: function(route, name, callback) { 895 | Backbone.history || (Backbone.history = new History); 896 | if (!_.isRegExp(route)) route = this._routeToRegExp(route); 897 | if (!callback) callback = this[name]; 898 | Backbone.history.route(route, _.bind(function(fragment) { 899 | var args = this._extractParameters(route, fragment); 900 | callback && callback.apply(this, args); 901 | this.trigger.apply(this, ['route:' + name].concat(args)); 902 | Backbone.history.trigger('route', this, name, args); 903 | }, this)); 904 | return this; 905 | }, 906 | 907 | // Simple proxy to `Backbone.history` to save a fragment into the history. 908 | navigate: function(fragment, options) { 909 | Backbone.history.navigate(fragment, options); 910 | }, 911 | 912 | // Bind all defined routes to `Backbone.history`. We have to reverse the 913 | // order of the routes here to support behavior where the most general 914 | // routes can be defined at the bottom of the route map. 915 | _bindRoutes: function() { 916 | if (!this.routes) return; 917 | var routes = []; 918 | for (var route in this.routes) { 919 | routes.unshift([route, this.routes[route]]); 920 | } 921 | for (var i = 0, l = routes.length; i < l; i++) { 922 | this.route(routes[i][0], routes[i][1], this[routes[i][1]]); 923 | } 924 | }, 925 | 926 | // Convert a route string into a regular expression, suitable for matching 927 | // against the current location hash. 928 | _routeToRegExp: function(route) { 929 | route = route.replace(escapeRegExp, '\\$&') 930 | .replace(namedParam, '([^\/]+)') 931 | .replace(splatParam, '(.*?)'); 932 | return new RegExp('^' + route + '$'); 933 | }, 934 | 935 | // Given a route, and a URL fragment that it matches, return the array of 936 | // extracted parameters. 937 | _extractParameters: function(route, fragment) { 938 | return route.exec(fragment).slice(1); 939 | } 940 | 941 | }); 942 | 943 | // Backbone.History 944 | // ---------------- 945 | 946 | // Handles cross-browser history management, based on URL fragments. If the 947 | // browser does not support `onhashchange`, falls back to polling. 948 | var History = Backbone.History = function() { 949 | this.handlers = []; 950 | _.bindAll(this, 'checkUrl'); 951 | }; 952 | 953 | // Cached regex for cleaning leading hashes and slashes . 954 | var routeStripper = /^[#\/]/; 955 | 956 | // Cached regex for detecting MSIE. 957 | var isExplorer = /msie [\w.]+/; 958 | 959 | // Has the history handling already been started? 960 | History.started = false; 961 | 962 | // Set up all inheritable **Backbone.History** properties and methods. 963 | _.extend(History.prototype, Events, { 964 | 965 | // The default interval to poll for hash changes, if necessary, is 966 | // twenty times a second. 967 | interval: 50, 968 | 969 | // Gets the true hash value. Cannot use location.hash directly due to bug 970 | // in Firefox where location.hash will always be decoded. 971 | getHash: function(windowOverride) { 972 | var loc = windowOverride ? windowOverride.location : window.location; 973 | var match = loc.href.match(/#(.*)$/); 974 | return match ? match[1] : ''; 975 | }, 976 | 977 | // Get the cross-browser normalized URL fragment, either from the URL, 978 | // the hash, or the override. 979 | getFragment: function(fragment, forcePushState) { 980 | if (fragment == null) { 981 | if (this._hasPushState || forcePushState) { 982 | fragment = window.location.pathname; 983 | var search = window.location.search; 984 | if (search) fragment += search; 985 | } else { 986 | fragment = this.getHash(); 987 | } 988 | } 989 | if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); 990 | return fragment.replace(routeStripper, ''); 991 | }, 992 | 993 | // Start the hash change handling, returning `true` if the current URL matches 994 | // an existing route, and `false` otherwise. 995 | start: function(options) { 996 | if (History.started) throw new Error("Backbone.history has already been started"); 997 | History.started = true; 998 | 999 | // Figure out the initial configuration. Do we need an iframe? 1000 | // Is pushState desired ... is it available? 1001 | this.options = _.extend({}, {root: '/'}, this.options, options); 1002 | this._wantsHashChange = this.options.hashChange !== false; 1003 | this._wantsPushState = !!this.options.pushState; 1004 | this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); 1005 | var fragment = this.getFragment(); 1006 | var docMode = document.documentMode; 1007 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); 1008 | 1009 | if (oldIE) { 1010 | this.iframe = $('