├── .gitignore ├── .travis.yml ├── package.json ├── gulpfile.js ├── demo ├── index.html ├── demo.js └── lib │ ├── jquery.tmpl.js │ ├── underscore.js │ ├── backbone.js │ └── jquery.min.js ├── .jshintrc ├── README.md └── backbone-parse.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 0.10 4 | script: gulp -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "chai": "^2.1.0", 4 | "gulp": "^3.8.11", 5 | "gulp-jshint": "^1.2.5" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | var jshint = require('gulp-jshint'); 2 | var gulp = require('gulp'); 3 | 4 | gulp.task('lint', function() { 5 | return gulp.src('./backbone-parse.js') 6 | .pipe(jshint()) 7 | .pipe(jshint.reporter('default')) 8 | .pipe(jshint.reporter('fail')); 9 | }); 10 | 11 | gulp.task('default', ['lint']); -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 14 |
15 | 16 | 17 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | /* 3 | * ENVIRONMENTS 4 | * ================= 5 | */ 6 | 7 | // Define globals exposed by modern browsers. 8 | "browser": true, 9 | 10 | // Define globals exposed by jQuery. 11 | "jquery": true, 12 | 13 | // Define globals exposed by Node.js. 14 | "node": true, 15 | 16 | /* 17 | * ENFORCING OPTIONS 18 | * ================= 19 | */ 20 | 21 | // Force all variable names to use either camelCase style or UPPER_CASE 22 | // with underscores. 23 | "camelcase": true, 24 | 25 | // Prohibit use of == and != in favor of === and !==. 26 | "eqeqeq": true, 27 | 28 | // Enforce tab width of 2 spaces. 29 | "indent": 2, 30 | 31 | // Prohibit use of a variable before it is defined. 32 | "latedef": true, 33 | 34 | // Enforce line length to 80 characters 35 | "maxlen": 80, 36 | 37 | // Require capitalized names for constructor functions. 38 | "newcap": true, 39 | 40 | // Enforce use of single quotation marks for strings. 41 | "quotmark": "single", 42 | 43 | // Enforce placing 'use strict' at the top function scope 44 | "strict": true, 45 | 46 | // Prohibit use of explicitly undeclared variables. 47 | "undef": true, 48 | 49 | // Warn when variables are defined but never used. 50 | "unused": true, 51 | 52 | /* 53 | * RELAXING OPTIONS 54 | * ================= 55 | */ 56 | 57 | // Suppress warnings about == null comparisons. 58 | "eqnull": true 59 | } -------------------------------------------------------------------------------- /demo/demo.js: -------------------------------------------------------------------------------- 1 | 2 | Item = Backbone.Model.extend({_parse_class_name: "Item"}); 3 | 4 | ItemCollection = Backbone.Collection.extend({ 5 | model: Item, 6 | _parse_class_name: "Item" 7 | }); 8 | 9 | ItemListView = Backbone.View.extend({ 10 | tagName: "ul", 11 | events: { 12 | "click a": "clicked" 13 | }, 14 | 15 | clicked: function(e){ 16 | e.preventDefault(); 17 | var id = $(e.currentTarget).data("id"); 18 | var item = this.collection.get(id); 19 | var name = item.get("name"); 20 | alert(name); 21 | }, 22 | 23 | render: function(){ 24 | var template = $("#item-template"); 25 | var el = $(this.el); 26 | this.collection.each(function(model){ 27 | var html = template.tmpl(model.toJSON()); 28 | el.append(html); 29 | }); 30 | } 31 | }); 32 | 33 | 34 | 35 | 36 | $(function() { 37 | var items = new ItemCollection(); 38 | items.fetch({ 39 | success: function() { 40 | var view = new ItemListView({collection: items}); 41 | view.render(); 42 | $("#showIt").html(view.el); 43 | }, 44 | query: {"in_stock":true} 45 | }); 46 | 47 | // var item = new Item({id: "86YC9d8K9v", name:"sayonee"}); 48 | // item.fetch({ 49 | // success: function() { 50 | // console.log(item.toJSON()); 51 | // } 52 | // }); 53 | 54 | }); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # backbone-parse 2 | 3 | backbone-parse overrides the Backbone.Sync method to automatically persist your backbone models on Parse using their REST API. Saving you from all the manual plumbing. 4 | 5 | ## Installation 6 | 7 | ### Step 1: 8 | 9 | Download backbone-parse.js and include it in your application after backbone.js e.g. 10 | ```html 11 | 12 | 13 | ``` 14 | 15 | 16 | ### Step 2: 17 | Open backbone-parse.js and replace following at the top with your Parse credentials: 18 | 19 | ```javascript 20 | var application_id = "CkWCHMSOgyqoNKoIc5hu09uvdZcJ9rpHJD4iwhxI"; 21 | var rest_api_key = "H5SIwarTRXqd07C0OIZPbcRTYTNLKsjFAJt5PrFY"; 22 | var api_version = "1"; 23 | 24 | ``` 25 | 26 | 27 | ## How to use it: 28 | 29 | ### Initialization: 30 | Create a Backbone model and set the parse class name: 31 | 32 | ```javascript 33 | var Item = new Backbone.Model({ 34 | _parse_class_name: "Item"; 35 | }); 36 | ``` 37 | 38 | Similarly for Collections: 39 | 40 | ```javascript 41 | var ItemsCollection = new Backbone.Collection({ 42 | _parse_class_name: "Item"; 43 | }); 44 | ``` 45 | 46 | This class name will specify backbone-parse which class persists this model on the Parse server. It is case sensitive. If the class doesn't already exists, Parse will automatically create one. 47 | 48 | If the class name is not specified, then the model will be persisted using the default Backbone Sync (i.e. you'll need to specify a url) 49 | 50 | ### Querying 51 | Parse.com provides an API to query your data. 52 | 53 | backbone-parse provides an easier method for specifying query constraints*. All you need is to pass the constraints in ```fetch``` method of ```Backbone.Collection```. e.g. 54 | 55 | ```javascript 56 | var ItemCollection = new Backbone.Collection({ 57 | _parse_class_name: "Item" 58 | }); 59 | 60 | var items = new ItemCollection(); 61 | items.fetch({ 62 | query: {"in_stock":true} 63 | }); 64 | ``` 65 | This will fetch all the items which are in stock. 66 | For details about what constraints you can pass, read: https://parse.com/docs/rest#queries 67 | 68 | Feedback welcome. 69 | 70 | 71 | ## TODO: 72 | 73 | - tests(!) 74 | - extend Backbone.Model to tackle Parse User objects 75 | 76 | 77 | ## License 78 | 79 | Distributed under [MIT license](http://mutedsolutions.mit-license.org/). 80 | 81 | ------- 82 | 83 | *inspired by: http://houseofbilz.com/archives/2011/11/07/making-backbone-js-work-with-parse-com/ 84 | -------------------------------------------------------------------------------- /backbone-parse.js: -------------------------------------------------------------------------------- 1 | /********** PARSE API ACCESS CREDENTIALS **********/ 2 | 3 | var application_id = "CkWCHMSOgyqoNKoIc5hu09uvdZcJ9rpHJD4iwhxI"; 4 | var rest_api_key = "H5SIwarTRXqd07C0OIZPbcRTYTNLKsjFAJt5PrFY"; 5 | var api_version = "1"; 6 | 7 | /******************* END *************************/ 8 | 9 | (function() { 10 | 11 | /* 12 | Replace the toJSON method of Backbone.Model with our version 13 | 14 | This method removes the "createdAt" and "updatedAt" keys from the JSON version 15 | because otherwise the PUT requests to Parse fails. 16 | */ 17 | var original_toJSON =Backbone.Model.prototype.toJSON; 18 | var ParseModel = { 19 | toJSON : function(options) { 20 | _parse_class_name = this.__proto__._parse_class_name; 21 | data = original_toJSON.call(this,options); 22 | delete data.createdAt 23 | delete data.updatedAt 24 | return data 25 | }, 26 | 27 | idAttribute: "objectId" 28 | }; 29 | _.extend(Backbone.Model.prototype, ParseModel); 30 | 31 | /* 32 | Replace the parse method of Backbone.Collection 33 | 34 | Backbone Collection expects to get a JSON array when fetching. 35 | Parse returns a JSON object with key "results" and value being the array. 36 | */ 37 | original_parse =Backbone.Collection.prototype.parse; 38 | var ParseCollection = { 39 | parse : function(options) { 40 | _parse_class_name = this.__proto__._parse_class_name; 41 | data = original_parse.call(this,options); 42 | if (_parse_class_name && data.results) { 43 | //do your thing 44 | return data.results; 45 | } 46 | else { 47 | //return original 48 | return data; 49 | } 50 | } 51 | }; 52 | _.extend(Backbone.Collection.prototype, ParseCollection); 53 | 54 | /* 55 | Method to HTTP Type Map 56 | */ 57 | var methodMap = { 58 | 'create': 'POST', 59 | 'update': 'PUT', 60 | 'delete': 'DELETE', 61 | 'read': 'GET' 62 | }; 63 | 64 | /* 65 | Override the default Backbone.sync 66 | */ 67 | var ajaxSync = Backbone.sync; 68 | Backbone.sync = function(method, model, options) { 69 | 70 | 71 | var object_id = model.models? "" : model.id; //get id if it is not a Backbone Collection 72 | 73 | 74 | var class_name = model.__proto__._parse_class_name; 75 | if (!class_name) { 76 | return ajaxSync(method, model, options) //It's a not a Parse-backed model, use default sync 77 | } 78 | 79 | // create request parameteres 80 | var type = methodMap[method]; 81 | options || (options = {}); 82 | var base_url = "https://api.parse.com/" + api_version + "/classes"; 83 | var url = base_url + "/" + class_name + "/"; 84 | if (method != "create") { 85 | url = url + object_id; 86 | } 87 | 88 | //Setup data 89 | var data ; 90 | if (!options.data && model && (method == 'create' || method == 'update')) { 91 | data = JSON.stringify(model.toJSON()); 92 | } 93 | else if (options.query && method == "read") { //query for Parse.com objects 94 | data = encodeURI("where=" + JSON.stringify(options.query)); 95 | } 96 | 97 | var request = { 98 | //data 99 | contentType: "application/json", 100 | processData: false, 101 | dataType: 'json', 102 | data: data, 103 | 104 | //action 105 | url: url, 106 | type: type, 107 | 108 | //authentication 109 | headers: { 110 | "X-Parse-Application-Id": application_id, 111 | "X-Parse-REST-API-Key": rest_api_key 112 | } 113 | }; 114 | 115 | return $.ajax(_.extend(options, request)); 116 | }; 117 | 118 | })(); 119 | -------------------------------------------------------------------------------- /demo/lib/jquery.tmpl.js: -------------------------------------------------------------------------------- 1 | /* 2 | * jQuery Templating Plugin 3 | * Copyright 2010, John Resig 4 | * Dual licensed under the MIT or GPL Version 2 licenses. 5 | */ 6 | (function( jQuery, undefined ){ 7 | var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /, 8 | newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = []; 9 | 10 | function newTmplItem( options, parentItem, fn, data ) { 11 | // Returns a template item data structure for a new rendered instance of a template (a 'template item'). 12 | // The content field is a hierarchical array of strings and nested items (to be 13 | // removed and replaced by nodes field of dom elements, once inserted in DOM). 14 | var newItem = { 15 | data: data || (parentItem ? parentItem.data : {}), 16 | _wrap: parentItem ? parentItem._wrap : null, 17 | tmpl: null, 18 | parent: parentItem || null, 19 | nodes: [], 20 | calls: tiCalls, 21 | nest: tiNest, 22 | wrap: tiWrap, 23 | html: tiHtml, 24 | update: tiUpdate 25 | }; 26 | if ( options ) { 27 | jQuery.extend( newItem, options, { nodes: [], parent: parentItem } ); 28 | } 29 | if ( fn ) { 30 | // Build the hierarchical content to be used during insertion into DOM 31 | newItem.tmpl = fn; 32 | newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem ); 33 | newItem.key = ++itemKey; 34 | // Keep track of new template item, until it is stored as jQuery Data on DOM element 35 | (stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem; 36 | } 37 | return newItem; 38 | } 39 | 40 | // Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core). 41 | jQuery.each({ 42 | appendTo: "append", 43 | prependTo: "prepend", 44 | insertBefore: "before", 45 | insertAfter: "after", 46 | replaceAll: "replaceWith" 47 | }, function( name, original ) { 48 | jQuery.fn[ name ] = function( selector ) { 49 | var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems, 50 | parent = this.length === 1 && this[0].parentNode; 51 | 52 | appendToTmplItems = newTmplItems || {}; 53 | if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { 54 | insert[ original ]( this[0] ); 55 | ret = this; 56 | } else { 57 | for ( i = 0, l = insert.length; i < l; i++ ) { 58 | cloneIndex = i; 59 | elems = (i > 0 ? this.clone(true) : this).get(); 60 | jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); 61 | ret = ret.concat( elems ); 62 | } 63 | cloneIndex = 0; 64 | ret = this.pushStack( ret, name, insert.selector ); 65 | } 66 | tmplItems = appendToTmplItems; 67 | appendToTmplItems = null; 68 | jQuery.tmpl.complete( tmplItems ); 69 | return ret; 70 | }; 71 | }); 72 | 73 | jQuery.fn.extend({ 74 | // Use first wrapped element as template markup. 75 | // Return wrapped set of template items, obtained by rendering template against data. 76 | tmpl: function( data, options, parentItem ) { 77 | return jQuery.tmpl( this[0], data, options, parentItem ); 78 | }, 79 | 80 | // Find which rendered template item the first wrapped DOM element belongs to 81 | tmplItem: function() { 82 | return jQuery.tmplItem( this[0] ); 83 | }, 84 | 85 | // Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template. 86 | template: function( name ) { 87 | return jQuery.template( name, this[0] ); 88 | }, 89 | 90 | domManip: function( args, table, callback, options ) { 91 | // This appears to be a bug in the appendTo, etc. implementation 92 | // it should be doing .call() instead of .apply(). See #6227 93 | if ( args[0] && args[0].nodeType ) { 94 | var dmArgs = jQuery.makeArray( arguments ), argsLength = args.length, i = 0, tmplItem; 95 | while ( i < argsLength && !(tmplItem = jQuery.data( args[i++], "tmplItem" ))) {} 96 | if ( argsLength > 1 ) { 97 | dmArgs[0] = [jQuery.makeArray( args )]; 98 | } 99 | if ( tmplItem && cloneIndex ) { 100 | dmArgs[2] = function( fragClone ) { 101 | // Handler called by oldManip when rendered template has been inserted into DOM. 102 | jQuery.tmpl.afterManip( this, fragClone, callback ); 103 | }; 104 | } 105 | oldManip.apply( this, dmArgs ); 106 | } else { 107 | oldManip.apply( this, arguments ); 108 | } 109 | cloneIndex = 0; 110 | if ( !appendToTmplItems ) { 111 | jQuery.tmpl.complete( newTmplItems ); 112 | } 113 | return this; 114 | } 115 | }); 116 | 117 | jQuery.extend({ 118 | // Return wrapped set of template items, obtained by rendering template against data. 119 | tmpl: function( tmpl, data, options, parentItem ) { 120 | var ret, topLevel = !parentItem; 121 | if ( topLevel ) { 122 | // This is a top-level tmpl call (not from a nested template using {{tmpl}}) 123 | parentItem = topTmplItem; 124 | tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl ); 125 | wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level 126 | } else if ( !tmpl ) { 127 | // The template item is already associated with DOM - this is a refresh. 128 | // Re-evaluate rendered template for the parentItem 129 | tmpl = parentItem.tmpl; 130 | newTmplItems[parentItem.key] = parentItem; 131 | parentItem.nodes = []; 132 | if ( parentItem.wrapped ) { 133 | updateWrapped( parentItem, parentItem.wrapped ); 134 | } 135 | // Rebuild, without creating a new template item 136 | return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) )); 137 | } 138 | if ( !tmpl ) { 139 | return []; // Could throw... 140 | } 141 | if ( typeof data === "function" ) { 142 | data = data.call( parentItem || {} ); 143 | } 144 | if ( options && options.wrapped ) { 145 | updateWrapped( options, options.wrapped ); 146 | } 147 | ret = jQuery.isArray( data ) ? 148 | jQuery.map( data, function( dataItem ) { 149 | return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null; 150 | }) : 151 | [ newTmplItem( options, parentItem, tmpl, data ) ]; 152 | return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret; 153 | }, 154 | 155 | // Return rendered template item for an element. 156 | tmplItem: function( elem ) { 157 | var tmplItem; 158 | if ( elem instanceof jQuery ) { 159 | elem = elem[0]; 160 | } 161 | while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {} 162 | return tmplItem || topTmplItem; 163 | }, 164 | 165 | // Set: 166 | // Use $.template( name, tmpl ) to cache a named template, 167 | // where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc. 168 | // Use $( "selector" ).template( name ) to provide access by name to a script block template declaration. 169 | 170 | // Get: 171 | // Use $.template( name ) to access a cached template. 172 | // Also $( selectorToScriptBlock ).template(), or $.template( null, templateString ) 173 | // will return the compiled template, without adding a name reference. 174 | // If templateString includes at least one HTML tag, $.template( templateString ) is equivalent 175 | // to $.template( null, templateString ) 176 | template: function( name, tmpl ) { 177 | if (tmpl) { 178 | // Compile template and associate with name 179 | if ( typeof tmpl === "string" ) { 180 | // This is an HTML string being passed directly in. 181 | tmpl = buildTmplFn( tmpl ) 182 | } else if ( tmpl instanceof jQuery ) { 183 | tmpl = tmpl[0] || {}; 184 | } 185 | if ( tmpl.nodeType ) { 186 | // If this is a template block, use cached copy, or generate tmpl function and cache. 187 | tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML )); 188 | } 189 | return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl; 190 | } 191 | // Return named compiled template 192 | return name ? (typeof name !== "string" ? jQuery.template( null, name ): 193 | (jQuery.template[name] || 194 | // If not in map, treat as a selector. (If integrated with core, use quickExpr.exec) 195 | jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null; 196 | }, 197 | 198 | encode: function( text ) { 199 | // Do HTML encoding replacing < > & and ' and " by corresponding entities. 200 | return ("" + text).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'"); 201 | } 202 | }); 203 | 204 | jQuery.extend( jQuery.tmpl, { 205 | tag: { 206 | "tmpl": { 207 | _default: { $2: "null" }, 208 | open: "if($notnull_1){_=_.concat($item.nest($1,$2));}" 209 | // tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions) 210 | // This means that {{tmpl foo}} treats foo as a template (which IS a function). 211 | // Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}. 212 | }, 213 | "wrap": { 214 | _default: { $2: "null" }, 215 | open: "$item.calls(_,$1,$2);_=[];", 216 | close: "call=$item.calls();_=call._.concat($item.wrap(call,_));" 217 | }, 218 | "each": { 219 | _default: { $2: "$index, $value" }, 220 | open: "if($notnull_1){$.each($1a,function($2){with(this){", 221 | close: "}});}" 222 | }, 223 | "if": { 224 | open: "if(($notnull_1) && $1a){", 225 | close: "}" 226 | }, 227 | "else": { 228 | _default: { $1: "true" }, 229 | open: "}else if(($notnull_1) && $1a){" 230 | }, 231 | "html": { 232 | // Unecoded expression evaluation. 233 | open: "if($notnull_1){_.push($1a);}" 234 | }, 235 | "=": { 236 | // Encoded expression evaluation. Abbreviated form is ${}. 237 | _default: { $1: "$data" }, 238 | open: "if($notnull_1){_.push($.encode($1a));}" 239 | }, 240 | "!": { 241 | // Comment tag. Skipped by parser 242 | open: "" 243 | } 244 | }, 245 | 246 | // This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events 247 | complete: function( items ) { 248 | newTmplItems = {}; 249 | }, 250 | 251 | // Call this from code which overrides domManip, or equivalent 252 | // Manage cloning/storing template items etc. 253 | afterManip: function afterManip( elem, fragClone, callback ) { 254 | // Provides cloned fragment ready for fixup prior to and after insertion into DOM 255 | var content = fragClone.nodeType === 11 ? 256 | jQuery.makeArray(fragClone.childNodes) : 257 | fragClone.nodeType === 1 ? [fragClone] : []; 258 | 259 | // Return fragment to original caller (e.g. append) for DOM insertion 260 | callback.call( elem, fragClone ); 261 | 262 | // Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data. 263 | storeTmplItems( content ); 264 | cloneIndex++; 265 | } 266 | }); 267 | 268 | //========================== Private helper functions, used by code above ========================== 269 | 270 | function build( tmplItem, nested, content ) { 271 | // Convert hierarchical content into flat string array 272 | // and finally return array of fragments ready for DOM insertion 273 | var frag, ret = content ? jQuery.map( content, function( item ) { 274 | return (typeof item === "string") ? 275 | // Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM. 276 | (tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) : 277 | // This is a child template item. Build nested template. 278 | build( item, tmplItem, item._ctnt ); 279 | }) : 280 | // If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}. 281 | tmplItem; 282 | if ( nested ) { 283 | return ret; 284 | } 285 | 286 | // top-level template 287 | ret = ret.join(""); 288 | 289 | // Support templates which have initial or final text nodes, or consist only of text 290 | // Also support HTML entities within the HTML markup. 291 | ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) { 292 | frag = jQuery( middle ).get(); 293 | 294 | storeTmplItems( frag ); 295 | if ( before ) { 296 | frag = unencode( before ).concat(frag); 297 | } 298 | if ( after ) { 299 | frag = frag.concat(unencode( after )); 300 | } 301 | }); 302 | return frag ? frag : unencode( ret ); 303 | } 304 | 305 | function unencode( text ) { 306 | // Use createElement, since createTextNode will not render HTML entities correctly 307 | var el = document.createElement( "div" ); 308 | el.innerHTML = text; 309 | return jQuery.makeArray(el.childNodes); 310 | } 311 | 312 | // Generate a reusable function that will serve to render a template against data 313 | function buildTmplFn( markup ) { 314 | return new Function("jQuery","$item", 315 | "var $=jQuery,call,_=[],$data=$item.data;" + 316 | 317 | // Introduce the data as local variables using with(){} 318 | "with($data){_.push('" + 319 | 320 | // Convert the template into pure JavaScript 321 | jQuery.trim(markup) 322 | .replace( /([\\'])/g, "\\$1" ) 323 | .replace( /[\r\t\n]/g, " " ) 324 | .replace( /\$\{([^\}]*)\}/g, "{{= $1}}" ) 325 | .replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g, 326 | function( all, slash, type, fnargs, target, parens, args ) { 327 | var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect; 328 | if ( !tag ) { 329 | throw "Template command not found: " + type; 330 | } 331 | def = tag._default || []; 332 | if ( parens && !/\w$/.test(target)) { 333 | target += parens; 334 | parens = ""; 335 | } 336 | if ( target ) { 337 | target = unescape( target ); 338 | args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : ""); 339 | // Support for target being things like a.toLowerCase(); 340 | // In that case don't call with template item as 'this' pointer. Just evaluate... 341 | expr = parens ? (target.indexOf(".") > -1 ? target + parens : ("(" + target + ").call($item" + args)) : target; 342 | exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))"; 343 | } else { 344 | exprAutoFnDetect = expr = def.$1 || "null"; 345 | } 346 | fnargs = unescape( fnargs ); 347 | return "');" + 348 | tag[ slash ? "close" : "open" ] 349 | .split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" ) 350 | .split( "$1a" ).join( exprAutoFnDetect ) 351 | .split( "$1" ).join( expr ) 352 | .split( "$2" ).join( fnargs ? 353 | fnargs.replace( /\s*([^\(]+)\s*(\((.*?)\))?/g, function( all, name, parens, params ) { 354 | params = params ? ("," + params + ")") : (parens ? ")" : ""); 355 | return params ? ("(" + name + ").call($item" + params) : all; 356 | }) 357 | : (def.$2||"") 358 | ) + 359 | "_.push('"; 360 | }) + 361 | "');}return _;" 362 | ); 363 | } 364 | function updateWrapped( options, wrapped ) { 365 | // Build the wrapped content. 366 | options._wrap = build( options, true, 367 | // Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string. 368 | jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()] 369 | ).join(""); 370 | } 371 | 372 | function unescape( args ) { 373 | return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null; 374 | } 375 | function outerHtml( elem ) { 376 | var div = document.createElement("div"); 377 | div.appendChild( elem.cloneNode(true) ); 378 | return div.innerHTML; 379 | } 380 | 381 | // Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance. 382 | function storeTmplItems( content ) { 383 | var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m; 384 | for ( i = 0, l = content.length; i < l; i++ ) { 385 | if ( (elem = content[i]).nodeType !== 1 ) { 386 | continue; 387 | } 388 | elems = elem.getElementsByTagName("*"); 389 | for ( m = elems.length - 1; m >= 0; m-- ) { 390 | processItemKey( elems[m] ); 391 | } 392 | processItemKey( elem ); 393 | } 394 | function processItemKey( el ) { 395 | var pntKey, pntNode = el, pntItem, tmplItem, key; 396 | // Ensure that each rendered template inserted into the DOM has its own template item, 397 | if ( (key = el.getAttribute( tmplItmAtt ))) { 398 | while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { } 399 | if ( pntKey !== key ) { 400 | // The next ancestor with a _tmplitem expando is on a different key than this one. 401 | // So this is a top-level element within this template item 402 | // Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment. 403 | pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0; 404 | if ( !(tmplItem = newTmplItems[key]) ) { 405 | // The item is for wrapped content, and was copied from the temporary parent wrappedItem. 406 | tmplItem = wrappedItems[key]; 407 | tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode], null, true ); 408 | tmplItem.key = ++itemKey; 409 | newTmplItems[itemKey] = tmplItem; 410 | } 411 | if ( cloneIndex ) { 412 | cloneTmplItem( key ); 413 | } 414 | } 415 | el.removeAttribute( tmplItmAtt ); 416 | } else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) { 417 | // This was a rendered element, cloned during append or appendTo etc. 418 | // TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem. 419 | cloneTmplItem( tmplItem.key ); 420 | newTmplItems[tmplItem.key] = tmplItem; 421 | pntNode = jQuery.data( el.parentNode, "tmplItem" ); 422 | pntNode = pntNode ? pntNode.key : 0; 423 | } 424 | if ( tmplItem ) { 425 | pntItem = tmplItem; 426 | // Find the template item of the parent element. 427 | // (Using !=, not !==, since pntItem.key is number, and pntNode may be a string) 428 | while ( pntItem && pntItem.key != pntNode ) { 429 | // Add this element as a top-level node for this rendered template item, as well as for any 430 | // ancestor items between this item and the item of its parent element 431 | pntItem.nodes.push( el ); 432 | pntItem = pntItem.parent; 433 | } 434 | // Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering... 435 | delete tmplItem._ctnt; 436 | delete tmplItem._wrap; 437 | // Store template item as jQuery data on the element 438 | jQuery.data( el, "tmplItem", tmplItem ); 439 | } 440 | function cloneTmplItem( key ) { 441 | key = key + keySuffix; 442 | tmplItem = newClonedItems[key] = 443 | (newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent, null, true )); 444 | } 445 | } 446 | } 447 | 448 | //---- Helper functions for template item ---- 449 | 450 | function tiCalls( content, tmpl, data, options ) { 451 | if ( !content ) { 452 | return stack.pop(); 453 | } 454 | stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options }); 455 | } 456 | 457 | function tiNest( tmpl, data, options ) { 458 | // nested template, using {{tmpl}} tag 459 | return jQuery.tmpl( jQuery.template( tmpl ), data, options, this ); 460 | } 461 | 462 | function tiWrap( call, wrapped ) { 463 | // nested template, using {{wrap}} tag 464 | var options = call.options || {}; 465 | options.wrapped = wrapped; 466 | // Apply the template, which may incorporate wrapped content, 467 | return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item ); 468 | } 469 | 470 | function tiHtml( filter, textOnly ) { 471 | var wrapped = this._wrap; 472 | return jQuery.map( 473 | jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ), 474 | function(e) { 475 | return textOnly ? 476 | e.innerText || e.textContent : 477 | e.outerHTML || outerHtml(e); 478 | }); 479 | } 480 | 481 | function tiUpdate() { 482 | var coll = this.nodes; 483 | jQuery.tmpl( null, null, null, this).insertBefore( coll[0] ); 484 | jQuery( coll ).remove(); 485 | } 486 | })( jQuery ); 487 | -------------------------------------------------------------------------------- /demo/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**, with 52 | // backwards-compatibility for the old `require()` API. If we're in 53 | // the browser, add `_` as a global object via a string identifier, 54 | // for Closure Compiler "advanced" mode. 55 | if (typeof exports !== 'undefined') { 56 | if (typeof module !== 'undefined' && module.exports) { 57 | exports = module.exports = _; 58 | } 59 | exports._ = _; 60 | } else { 61 | root['_'] = _; 62 | } 63 | 64 | // Current version. 65 | _.VERSION = '1.3.3'; 66 | 67 | // Collection Functions 68 | // -------------------- 69 | 70 | // The cornerstone, an `each` implementation, aka `forEach`. 71 | // Handles objects with the built-in `forEach`, arrays, and raw objects. 72 | // Delegates to **ECMAScript 5**'s native `forEach` if available. 73 | var each = _.each = _.forEach = function(obj, iterator, context) { 74 | if (obj == null) return; 75 | if (nativeForEach && obj.forEach === nativeForEach) { 76 | obj.forEach(iterator, context); 77 | } else if (obj.length === +obj.length) { 78 | for (var i = 0, l = obj.length; i < l; i++) { 79 | if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; 80 | } 81 | } else { 82 | for (var key in obj) { 83 | if (_.has(obj, key)) { 84 | if (iterator.call(context, obj[key], key, obj) === breaker) return; 85 | } 86 | } 87 | } 88 | }; 89 | 90 | // Return the results of applying the iterator to each element. 91 | // Delegates to **ECMAScript 5**'s native `map` if available. 92 | _.map = _.collect = function(obj, iterator, context) { 93 | var results = []; 94 | if (obj == null) return results; 95 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); 96 | each(obj, function(value, index, list) { 97 | results[results.length] = iterator.call(context, value, index, list); 98 | }); 99 | if (obj.length === +obj.length) results.length = obj.length; 100 | return results; 101 | }; 102 | 103 | // **Reduce** builds up a single result from a list of values, aka `inject`, 104 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. 105 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { 106 | var initial = arguments.length > 2; 107 | if (obj == null) obj = []; 108 | if (nativeReduce && obj.reduce === nativeReduce) { 109 | if (context) iterator = _.bind(iterator, context); 110 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); 111 | } 112 | each(obj, function(value, index, list) { 113 | if (!initial) { 114 | memo = value; 115 | initial = true; 116 | } else { 117 | memo = iterator.call(context, memo, value, index, list); 118 | } 119 | }); 120 | if (!initial) throw new TypeError('Reduce of empty array with no initial value'); 121 | return memo; 122 | }; 123 | 124 | // The right-associative version of reduce, also known as `foldr`. 125 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available. 126 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) { 127 | var initial = arguments.length > 2; 128 | if (obj == null) obj = []; 129 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { 130 | if (context) iterator = _.bind(iterator, context); 131 | return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); 132 | } 133 | var reversed = _.toArray(obj).reverse(); 134 | if (context && !initial) iterator = _.bind(iterator, context); 135 | return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator); 136 | }; 137 | 138 | // Return the first value which passes a truth test. Aliased as `detect`. 139 | _.find = _.detect = function(obj, iterator, context) { 140 | var result; 141 | any(obj, function(value, index, list) { 142 | if (iterator.call(context, value, index, list)) { 143 | result = value; 144 | return true; 145 | } 146 | }); 147 | return result; 148 | }; 149 | 150 | // Return all the elements that pass a truth test. 151 | // Delegates to **ECMAScript 5**'s native `filter` if available. 152 | // Aliased as `select`. 153 | _.filter = _.select = function(obj, iterator, context) { 154 | var results = []; 155 | if (obj == null) return results; 156 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); 157 | each(obj, function(value, index, list) { 158 | if (iterator.call(context, value, index, list)) results[results.length] = value; 159 | }); 160 | return results; 161 | }; 162 | 163 | // Return all the elements for which a truth test fails. 164 | _.reject = function(obj, iterator, context) { 165 | var results = []; 166 | if (obj == null) return results; 167 | each(obj, function(value, index, list) { 168 | if (!iterator.call(context, value, index, list)) results[results.length] = value; 169 | }); 170 | return results; 171 | }; 172 | 173 | // Determine whether all of the elements match a truth test. 174 | // Delegates to **ECMAScript 5**'s native `every` if available. 175 | // Aliased as `all`. 176 | _.every = _.all = function(obj, iterator, context) { 177 | var result = true; 178 | if (obj == null) return result; 179 | if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); 180 | each(obj, function(value, index, list) { 181 | if (!(result = result && iterator.call(context, value, index, list))) return breaker; 182 | }); 183 | return !!result; 184 | }; 185 | 186 | // Determine if at least one element in the object matches a truth test. 187 | // Delegates to **ECMAScript 5**'s native `some` if available. 188 | // Aliased as `any`. 189 | var any = _.some = _.any = function(obj, iterator, context) { 190 | iterator || (iterator = _.identity); 191 | var result = false; 192 | if (obj == null) return result; 193 | if (nativeSome && obj.some === nativeSome) return obj.some(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 a given value is included in the array or object using `===`. 201 | // Aliased as `contains`. 202 | _.include = _.contains = function(obj, target) { 203 | var found = false; 204 | if (obj == null) return found; 205 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; 206 | found = any(obj, function(value) { 207 | return value === target; 208 | }); 209 | return found; 210 | }; 211 | 212 | // Invoke a method (with arguments) on every item in a collection. 213 | _.invoke = function(obj, method) { 214 | var args = slice.call(arguments, 2); 215 | return _.map(obj, function(value) { 216 | return (_.isFunction(method) ? method || value : value[method]).apply(value, args); 217 | }); 218 | }; 219 | 220 | // Convenience version of a common use case of `map`: fetching a property. 221 | _.pluck = function(obj, key) { 222 | return _.map(obj, function(value){ return value[key]; }); 223 | }; 224 | 225 | // Return the maximum element or (element-based computation). 226 | _.max = function(obj, iterator, context) { 227 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.max.apply(Math, obj); 228 | if (!iterator && _.isEmpty(obj)) return -Infinity; 229 | var result = {computed : -Infinity}; 230 | each(obj, function(value, index, list) { 231 | var computed = iterator ? iterator.call(context, value, index, list) : value; 232 | computed >= result.computed && (result = {value : value, computed : computed}); 233 | }); 234 | return result.value; 235 | }; 236 | 237 | // Return the minimum element (or element-based computation). 238 | _.min = function(obj, iterator, context) { 239 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0]) return Math.min.apply(Math, obj); 240 | if (!iterator && _.isEmpty(obj)) return Infinity; 241 | var result = {computed : Infinity}; 242 | each(obj, function(value, index, list) { 243 | var computed = iterator ? iterator.call(context, value, index, list) : value; 244 | computed < result.computed && (result = {value : value, computed : computed}); 245 | }); 246 | return result.value; 247 | }; 248 | 249 | // Shuffle an array. 250 | _.shuffle = function(obj) { 251 | var shuffled = [], rand; 252 | each(obj, function(value, index, list) { 253 | rand = Math.floor(Math.random() * (index + 1)); 254 | shuffled[index] = shuffled[rand]; 255 | shuffled[rand] = value; 256 | }); 257 | return shuffled; 258 | }; 259 | 260 | // Sort the object's values by a criterion produced by an iterator. 261 | _.sortBy = function(obj, val, context) { 262 | var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; 263 | return _.pluck(_.map(obj, function(value, index, list) { 264 | return { 265 | value : value, 266 | criteria : iterator.call(context, value, index, list) 267 | }; 268 | }).sort(function(left, right) { 269 | var a = left.criteria, b = right.criteria; 270 | if (a === void 0) return 1; 271 | if (b === void 0) return -1; 272 | return a < b ? -1 : a > b ? 1 : 0; 273 | }), 'value'); 274 | }; 275 | 276 | // Groups the object's values by a criterion. Pass either a string attribute 277 | // to group by, or a function that returns the criterion. 278 | _.groupBy = function(obj, val) { 279 | var result = {}; 280 | var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; 281 | each(obj, function(value, index) { 282 | var key = iterator(value, index); 283 | (result[key] || (result[key] = [])).push(value); 284 | }); 285 | return result; 286 | }; 287 | 288 | // Use a comparator function to figure out at what index an object should 289 | // be inserted so as to maintain order. Uses binary search. 290 | _.sortedIndex = function(array, obj, iterator) { 291 | iterator || (iterator = _.identity); 292 | var low = 0, high = array.length; 293 | while (low < high) { 294 | var mid = (low + high) >> 1; 295 | iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; 296 | } 297 | return low; 298 | }; 299 | 300 | // Safely convert anything iterable into a real, live array. 301 | _.toArray = function(obj) { 302 | if (!obj) return []; 303 | if (_.isArray(obj)) return slice.call(obj); 304 | if (_.isArguments(obj)) return slice.call(obj); 305 | if (obj.toArray && _.isFunction(obj.toArray)) return obj.toArray(); 306 | return _.values(obj); 307 | }; 308 | 309 | // Return the number of elements in an object. 310 | _.size = function(obj) { 311 | return _.isArray(obj) ? obj.length : _.keys(obj).length; 312 | }; 313 | 314 | // Array Functions 315 | // --------------- 316 | 317 | // Get the first element of an array. Passing **n** will return the first N 318 | // values in the array. Aliased as `head` and `take`. The **guard** check 319 | // allows it to work with `_.map`. 320 | _.first = _.head = _.take = function(array, n, guard) { 321 | return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; 322 | }; 323 | 324 | // Returns everything but the last entry of the array. Especcialy useful on 325 | // the arguments object. Passing **n** will return all the values in 326 | // the array, excluding the last N. The **guard** check allows it to work with 327 | // `_.map`. 328 | _.initial = function(array, n, guard) { 329 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); 330 | }; 331 | 332 | // Get the last element of an array. Passing **n** will return the last N 333 | // values in the array. The **guard** check allows it to work with `_.map`. 334 | _.last = function(array, n, guard) { 335 | if ((n != null) && !guard) { 336 | return slice.call(array, Math.max(array.length - n, 0)); 337 | } else { 338 | return array[array.length - 1]; 339 | } 340 | }; 341 | 342 | // Returns everything but the first entry of the array. Aliased as `tail`. 343 | // Especially useful on the arguments object. Passing an **index** will return 344 | // the rest of the values in the array from that index onward. The **guard** 345 | // check allows it to work with `_.map`. 346 | _.rest = _.tail = function(array, index, guard) { 347 | return slice.call(array, (index == null) || guard ? 1 : index); 348 | }; 349 | 350 | // Trim out all falsy values from an array. 351 | _.compact = function(array) { 352 | return _.filter(array, function(value){ return !!value; }); 353 | }; 354 | 355 | // Return a completely flattened version of an array. 356 | _.flatten = function(array, shallow) { 357 | return _.reduce(array, function(memo, value) { 358 | if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); 359 | memo[memo.length] = value; 360 | return memo; 361 | }, []); 362 | }; 363 | 364 | // Return a version of the array that does not contain the specified value(s). 365 | _.without = function(array) { 366 | return _.difference(array, slice.call(arguments, 1)); 367 | }; 368 | 369 | // Produce a duplicate-free version of the array. If the array has already 370 | // been sorted, you have the option of using a faster algorithm. 371 | // Aliased as `unique`. 372 | _.uniq = _.unique = function(array, isSorted, iterator) { 373 | var initial = iterator ? _.map(array, iterator) : array; 374 | var results = []; 375 | // The `isSorted` flag is irrelevant if the array only contains two elements. 376 | if (array.length < 3) isSorted = true; 377 | _.reduce(initial, function (memo, value, index) { 378 | if (isSorted ? _.last(memo) !== value || !memo.length : !_.include(memo, value)) { 379 | memo.push(value); 380 | results.push(array[index]); 381 | } 382 | return memo; 383 | }, []); 384 | return results; 385 | }; 386 | 387 | // Produce an array that contains the union: each distinct element from all of 388 | // the passed-in arrays. 389 | _.union = function() { 390 | return _.uniq(_.flatten(arguments, true)); 391 | }; 392 | 393 | // Produce an array that contains every item shared between all the 394 | // passed-in arrays. (Aliased as "intersect" for back-compat.) 395 | _.intersection = _.intersect = function(array) { 396 | var rest = slice.call(arguments, 1); 397 | return _.filter(_.uniq(array), function(item) { 398 | return _.every(rest, function(other) { 399 | return _.indexOf(other, item) >= 0; 400 | }); 401 | }); 402 | }; 403 | 404 | // Take the difference between one array and a number of other arrays. 405 | // Only the elements present in just the first array will remain. 406 | _.difference = function(array) { 407 | var rest = _.flatten(slice.call(arguments, 1), true); 408 | return _.filter(array, function(value){ return !_.include(rest, value); }); 409 | }; 410 | 411 | // Zip together multiple lists into a single array -- elements that share 412 | // an index go together. 413 | _.zip = function() { 414 | var args = slice.call(arguments); 415 | var length = _.max(_.pluck(args, 'length')); 416 | var results = new Array(length); 417 | for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); 418 | return results; 419 | }; 420 | 421 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), 422 | // we need this function. Return the position of the first occurrence of an 423 | // item in an array, or -1 if the item is not included in the array. 424 | // Delegates to **ECMAScript 5**'s native `indexOf` if available. 425 | // If the array is large and already in sort order, pass `true` 426 | // for **isSorted** to use binary search. 427 | _.indexOf = function(array, item, isSorted) { 428 | if (array == null) return -1; 429 | var i, l; 430 | if (isSorted) { 431 | i = _.sortedIndex(array, item); 432 | return array[i] === item ? i : -1; 433 | } 434 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); 435 | for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i; 436 | return -1; 437 | }; 438 | 439 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. 440 | _.lastIndexOf = function(array, item) { 441 | if (array == null) return -1; 442 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); 443 | var i = array.length; 444 | while (i--) if (i in array && array[i] === item) return i; 445 | return -1; 446 | }; 447 | 448 | // Generate an integer Array containing an arithmetic progression. A port of 449 | // the native Python `range()` function. See 450 | // [the Python documentation](http://docs.python.org/library/functions.html#range). 451 | _.range = function(start, stop, step) { 452 | if (arguments.length <= 1) { 453 | stop = start || 0; 454 | start = 0; 455 | } 456 | step = arguments[2] || 1; 457 | 458 | var len = Math.max(Math.ceil((stop - start) / step), 0); 459 | var idx = 0; 460 | var range = new Array(len); 461 | 462 | while(idx < len) { 463 | range[idx++] = start; 464 | start += step; 465 | } 466 | 467 | return range; 468 | }; 469 | 470 | // Function (ahem) Functions 471 | // ------------------ 472 | 473 | // Reusable constructor function for prototype setting. 474 | var ctor = function(){}; 475 | 476 | // Create a function bound to a given object (assigning `this`, and arguments, 477 | // optionally). Binding with arguments is also known as `curry`. 478 | // Delegates to **ECMAScript 5**'s native `Function.bind` if available. 479 | // We check for `func.bind` first, to fail fast when `func` is undefined. 480 | _.bind = function bind(func, context) { 481 | var bound, args; 482 | if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); 483 | if (!_.isFunction(func)) throw new TypeError; 484 | args = slice.call(arguments, 2); 485 | return bound = function() { 486 | if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); 487 | ctor.prototype = func.prototype; 488 | var self = new ctor; 489 | var result = func.apply(self, args.concat(slice.call(arguments))); 490 | if (Object(result) === result) return result; 491 | return self; 492 | }; 493 | }; 494 | 495 | // Bind all of an object's methods to that object. Useful for ensuring that 496 | // all callbacks defined on an object belong to it. 497 | _.bindAll = function(obj) { 498 | var funcs = slice.call(arguments, 1); 499 | if (funcs.length == 0) funcs = _.functions(obj); 500 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); 501 | return obj; 502 | }; 503 | 504 | // Memoize an expensive function by storing its results. 505 | _.memoize = function(func, hasher) { 506 | var memo = {}; 507 | hasher || (hasher = _.identity); 508 | return function() { 509 | var key = hasher.apply(this, arguments); 510 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); 511 | }; 512 | }; 513 | 514 | // Delays a function for the given number of milliseconds, and then calls 515 | // it with the arguments supplied. 516 | _.delay = function(func, wait) { 517 | var args = slice.call(arguments, 2); 518 | return setTimeout(function(){ return func.apply(null, args); }, wait); 519 | }; 520 | 521 | // Defers a function, scheduling it to run after the current call stack has 522 | // cleared. 523 | _.defer = function(func) { 524 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); 525 | }; 526 | 527 | // Returns a function, that, when invoked, will only be triggered at most once 528 | // during a given window of time. 529 | _.throttle = function(func, wait) { 530 | var context, args, timeout, throttling, more, result; 531 | var whenDone = _.debounce(function(){ more = throttling = false; }, wait); 532 | return function() { 533 | context = this; args = arguments; 534 | var later = function() { 535 | timeout = null; 536 | if (more) func.apply(context, args); 537 | whenDone(); 538 | }; 539 | if (!timeout) timeout = setTimeout(later, wait); 540 | if (throttling) { 541 | more = true; 542 | } else { 543 | result = func.apply(context, args); 544 | } 545 | whenDone(); 546 | throttling = true; 547 | return result; 548 | }; 549 | }; 550 | 551 | // Returns a function, that, as long as it continues to be invoked, will not 552 | // be triggered. The function will be called after it stops being called for 553 | // N milliseconds. If `immediate` is passed, trigger the function on the 554 | // leading edge, instead of the trailing. 555 | _.debounce = function(func, wait, immediate) { 556 | var timeout; 557 | return function() { 558 | var context = this, args = arguments; 559 | var later = function() { 560 | timeout = null; 561 | if (!immediate) func.apply(context, args); 562 | }; 563 | if (immediate && !timeout) func.apply(context, args); 564 | clearTimeout(timeout); 565 | timeout = setTimeout(later, wait); 566 | }; 567 | }; 568 | 569 | // Returns a function that will be executed at most one time, no matter how 570 | // often you call it. Useful for lazy initialization. 571 | _.once = function(func) { 572 | var ran = false, memo; 573 | return function() { 574 | if (ran) return memo; 575 | ran = true; 576 | return memo = func.apply(this, arguments); 577 | }; 578 | }; 579 | 580 | // Returns the first function passed as an argument to the second, 581 | // allowing you to adjust arguments, run code before and after, and 582 | // conditionally execute the original function. 583 | _.wrap = function(func, wrapper) { 584 | return function() { 585 | var args = [func].concat(slice.call(arguments, 0)); 586 | return wrapper.apply(this, args); 587 | }; 588 | }; 589 | 590 | // Returns a function that is the composition of a list of functions, each 591 | // consuming the return value of the function that follows. 592 | _.compose = function() { 593 | var funcs = arguments; 594 | return function() { 595 | var args = arguments; 596 | for (var i = funcs.length - 1; i >= 0; i--) { 597 | args = [funcs[i].apply(this, args)]; 598 | } 599 | return args[0]; 600 | }; 601 | }; 602 | 603 | // Returns a function that will only be executed after being called N times. 604 | _.after = function(times, func) { 605 | if (times <= 0) return func(); 606 | return function() { 607 | if (--times < 1) { return func.apply(this, arguments); } 608 | }; 609 | }; 610 | 611 | // Object Functions 612 | // ---------------- 613 | 614 | // Retrieve the names of an object's properties. 615 | // Delegates to **ECMAScript 5**'s native `Object.keys` 616 | _.keys = nativeKeys || function(obj) { 617 | if (obj !== Object(obj)) throw new TypeError('Invalid object'); 618 | var keys = []; 619 | for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; 620 | return keys; 621 | }; 622 | 623 | // Retrieve the values of an object's properties. 624 | _.values = function(obj) { 625 | return _.map(obj, _.identity); 626 | }; 627 | 628 | // Return a sorted list of the function names available on the object. 629 | // Aliased as `methods` 630 | _.functions = _.methods = function(obj) { 631 | var names = []; 632 | for (var key in obj) { 633 | if (_.isFunction(obj[key])) names.push(key); 634 | } 635 | return names.sort(); 636 | }; 637 | 638 | // Extend a given object with all the properties in passed-in object(s). 639 | _.extend = function(obj) { 640 | each(slice.call(arguments, 1), function(source) { 641 | for (var prop in source) { 642 | obj[prop] = source[prop]; 643 | } 644 | }); 645 | return obj; 646 | }; 647 | 648 | // Return a copy of the object only containing the whitelisted properties. 649 | _.pick = function(obj) { 650 | var result = {}; 651 | each(_.flatten(slice.call(arguments, 1)), function(key) { 652 | if (key in obj) result[key] = obj[key]; 653 | }); 654 | return result; 655 | }; 656 | 657 | // Fill in a given object with default properties. 658 | _.defaults = function(obj) { 659 | each(slice.call(arguments, 1), function(source) { 660 | for (var prop in source) { 661 | if (obj[prop] == null) obj[prop] = source[prop]; 662 | } 663 | }); 664 | return obj; 665 | }; 666 | 667 | // Create a (shallow-cloned) duplicate of an object. 668 | _.clone = function(obj) { 669 | if (!_.isObject(obj)) return obj; 670 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 671 | }; 672 | 673 | // Invokes interceptor with the obj, and then returns obj. 674 | // The primary purpose of this method is to "tap into" a method chain, in 675 | // order to perform operations on intermediate results within the chain. 676 | _.tap = function(obj, interceptor) { 677 | interceptor(obj); 678 | return obj; 679 | }; 680 | 681 | // Internal recursive comparison function. 682 | function eq(a, b, stack) { 683 | // Identical objects are equal. `0 === -0`, but they aren't identical. 684 | // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. 685 | if (a === b) return a !== 0 || 1 / a == 1 / b; 686 | // A strict comparison is necessary because `null == undefined`. 687 | if (a == null || b == null) return a === b; 688 | // Unwrap any wrapped objects. 689 | if (a._chain) a = a._wrapped; 690 | if (b._chain) b = b._wrapped; 691 | // Invoke a custom `isEqual` method if one is provided. 692 | if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); 693 | if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); 694 | // Compare `[[Class]]` names. 695 | var className = toString.call(a); 696 | if (className != toString.call(b)) return false; 697 | switch (className) { 698 | // Strings, numbers, dates, and booleans are compared by value. 699 | case '[object String]': 700 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 701 | // equivalent to `new String("5")`. 702 | return a == String(b); 703 | case '[object Number]': 704 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 705 | // other numeric values. 706 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); 707 | case '[object Date]': 708 | case '[object Boolean]': 709 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 710 | // millisecond representations. Note that invalid dates with millisecond representations 711 | // of `NaN` are not equivalent. 712 | return +a == +b; 713 | // RegExps are compared by their source patterns and flags. 714 | case '[object RegExp]': 715 | return a.source == b.source && 716 | a.global == b.global && 717 | a.multiline == b.multiline && 718 | a.ignoreCase == b.ignoreCase; 719 | } 720 | if (typeof a != 'object' || typeof b != 'object') return false; 721 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 722 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 723 | var length = stack.length; 724 | while (length--) { 725 | // Linear search. Performance is inversely proportional to the number of 726 | // unique nested structures. 727 | if (stack[length] == a) return true; 728 | } 729 | // Add the first object to the stack of traversed objects. 730 | stack.push(a); 731 | var size = 0, result = true; 732 | // Recursively compare objects and arrays. 733 | if (className == '[object Array]') { 734 | // Compare array lengths to determine if a deep comparison is necessary. 735 | size = a.length; 736 | result = size == b.length; 737 | if (result) { 738 | // Deep compare the contents, ignoring non-numeric properties. 739 | while (size--) { 740 | // Ensure commutative equality for sparse arrays. 741 | if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; 742 | } 743 | } 744 | } else { 745 | // Objects with different constructors are not equivalent. 746 | if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; 747 | // Deep compare objects. 748 | for (var key in a) { 749 | if (_.has(a, key)) { 750 | // Count the expected number of properties. 751 | size++; 752 | // Deep compare each member. 753 | if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break; 754 | } 755 | } 756 | // Ensure that both objects contain the same number of properties. 757 | if (result) { 758 | for (key in b) { 759 | if (_.has(b, key) && !(size--)) break; 760 | } 761 | result = !size; 762 | } 763 | } 764 | // Remove the first object from the stack of traversed objects. 765 | stack.pop(); 766 | return result; 767 | } 768 | 769 | // Perform a deep comparison to check if two objects are equal. 770 | _.isEqual = function(a, b) { 771 | return eq(a, b, []); 772 | }; 773 | 774 | // Is a given array, string, or object empty? 775 | // An "empty" object has no enumerable own-properties. 776 | _.isEmpty = function(obj) { 777 | if (obj == null) return true; 778 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; 779 | for (var key in obj) if (_.has(obj, key)) return false; 780 | return true; 781 | }; 782 | 783 | // Is a given value a DOM element? 784 | _.isElement = function(obj) { 785 | return !!(obj && obj.nodeType == 1); 786 | }; 787 | 788 | // Is a given value an array? 789 | // Delegates to ECMA5's native Array.isArray 790 | _.isArray = nativeIsArray || function(obj) { 791 | return toString.call(obj) == '[object Array]'; 792 | }; 793 | 794 | // Is a given variable an object? 795 | _.isObject = function(obj) { 796 | return obj === Object(obj); 797 | }; 798 | 799 | // Is a given variable an arguments object? 800 | _.isArguments = function(obj) { 801 | return toString.call(obj) == '[object Arguments]'; 802 | }; 803 | if (!_.isArguments(arguments)) { 804 | _.isArguments = function(obj) { 805 | return !!(obj && _.has(obj, 'callee')); 806 | }; 807 | } 808 | 809 | // Is a given value a function? 810 | _.isFunction = function(obj) { 811 | return toString.call(obj) == '[object Function]'; 812 | }; 813 | 814 | // Is a given value a string? 815 | _.isString = function(obj) { 816 | return toString.call(obj) == '[object String]'; 817 | }; 818 | 819 | // Is a given value a number? 820 | _.isNumber = function(obj) { 821 | return toString.call(obj) == '[object Number]'; 822 | }; 823 | 824 | // Is a given object a finite number? 825 | _.isFinite = function(obj) { 826 | return _.isNumber(obj) && isFinite(obj); 827 | }; 828 | 829 | // Is the given value `NaN`? 830 | _.isNaN = function(obj) { 831 | // `NaN` is the only value for which `===` is not reflexive. 832 | return obj !== obj; 833 | }; 834 | 835 | // Is a given value a boolean? 836 | _.isBoolean = function(obj) { 837 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; 838 | }; 839 | 840 | // Is a given value a date? 841 | _.isDate = function(obj) { 842 | return toString.call(obj) == '[object Date]'; 843 | }; 844 | 845 | // Is the given value a regular expression? 846 | _.isRegExp = function(obj) { 847 | return toString.call(obj) == '[object RegExp]'; 848 | }; 849 | 850 | // Is a given value equal to null? 851 | _.isNull = function(obj) { 852 | return obj === null; 853 | }; 854 | 855 | // Is a given variable undefined? 856 | _.isUndefined = function(obj) { 857 | return obj === void 0; 858 | }; 859 | 860 | // Has own property? 861 | _.has = function(obj, key) { 862 | return hasOwnProperty.call(obj, key); 863 | }; 864 | 865 | // Utility Functions 866 | // ----------------- 867 | 868 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 869 | // previous owner. Returns a reference to the Underscore object. 870 | _.noConflict = function() { 871 | root._ = previousUnderscore; 872 | return this; 873 | }; 874 | 875 | // Keep the identity function around for default iterators. 876 | _.identity = function(value) { 877 | return value; 878 | }; 879 | 880 | // Run a function **n** times. 881 | _.times = function (n, iterator, context) { 882 | for (var i = 0; i < n; i++) iterator.call(context, i); 883 | }; 884 | 885 | // Escape a string for HTML interpolation. 886 | _.escape = function(string) { 887 | return (''+string).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/'); 888 | }; 889 | 890 | // If the value of the named property is a function then invoke it; 891 | // otherwise, return it. 892 | _.result = function(object, property) { 893 | if (object == null) return null; 894 | var value = object[property]; 895 | return _.isFunction(value) ? value.call(object) : value; 896 | }; 897 | 898 | // Add your own custom functions to the Underscore object, ensuring that 899 | // they're correctly added to the OOP wrapper as well. 900 | _.mixin = function(obj) { 901 | each(_.functions(obj), function(name){ 902 | addToWrapper(name, _[name] = obj[name]); 903 | }); 904 | }; 905 | 906 | // Generate a unique integer id (unique within the entire client session). 907 | // Useful for temporary DOM ids. 908 | var idCounter = 0; 909 | _.uniqueId = function(prefix) { 910 | var id = idCounter++; 911 | return prefix ? prefix + id : id; 912 | }; 913 | 914 | // By default, Underscore uses ERB-style template delimiters, change the 915 | // following template settings to use alternative delimiters. 916 | _.templateSettings = { 917 | evaluate : /<%([\s\S]+?)%>/g, 918 | interpolate : /<%=([\s\S]+?)%>/g, 919 | escape : /<%-([\s\S]+?)%>/g 920 | }; 921 | 922 | // When customizing `templateSettings`, if you don't want to define an 923 | // interpolation, evaluation or escaping regex, we need one that is 924 | // guaranteed not to match. 925 | var noMatch = /.^/; 926 | 927 | // Certain characters need to be escaped so that they can be put into a 928 | // string literal. 929 | var escapes = { 930 | '\\': '\\', 931 | "'": "'", 932 | 'r': '\r', 933 | 'n': '\n', 934 | 't': '\t', 935 | 'u2028': '\u2028', 936 | 'u2029': '\u2029' 937 | }; 938 | 939 | for (var p in escapes) escapes[escapes[p]] = p; 940 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; 941 | var unescaper = /\\(\\|'|r|n|t|u2028|u2029)/g; 942 | 943 | // Within an interpolation, evaluation, or escaping, remove HTML escaping 944 | // that had been previously added. 945 | var unescape = function(code) { 946 | return code.replace(unescaper, function(match, escape) { 947 | return escapes[escape]; 948 | }); 949 | }; 950 | 951 | // JavaScript micro-templating, similar to John Resig's implementation. 952 | // Underscore templating handles arbitrary delimiters, preserves whitespace, 953 | // and correctly escapes quotes within interpolated code. 954 | _.template = function(text, data, settings) { 955 | settings = _.defaults(settings || {}, _.templateSettings); 956 | 957 | // Compile the template source, taking care to escape characters that 958 | // cannot be included in a string literal and then unescape them in code 959 | // blocks. 960 | var source = "__p+='" + text 961 | .replace(escaper, function(match) { 962 | return '\\' + escapes[match]; 963 | }) 964 | .replace(settings.escape || noMatch, function(match, code) { 965 | return "'+\n_.escape(" + unescape(code) + ")+\n'"; 966 | }) 967 | .replace(settings.interpolate || noMatch, function(match, code) { 968 | return "'+\n(" + unescape(code) + ")+\n'"; 969 | }) 970 | .replace(settings.evaluate || noMatch, function(match, code) { 971 | return "';\n" + unescape(code) + "\n;__p+='"; 972 | }) + "';\n"; 973 | 974 | // If a variable is not specified, place data values in local scope. 975 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; 976 | 977 | source = "var __p='';" + 978 | "var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n" + 979 | source + "return __p;\n"; 980 | 981 | var render = new Function(settings.variable || 'obj', '_', source); 982 | if (data) return render(data, _); 983 | var template = function(data) { 984 | return render.call(this, data, _); 985 | }; 986 | 987 | // Provide the compiled function source as a convenience for build time 988 | // precompilation. 989 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + 990 | source + '}'; 991 | 992 | return template; 993 | }; 994 | 995 | // Add a "chain" function, which will delegate to the wrapper. 996 | _.chain = function(obj) { 997 | return _(obj).chain(); 998 | }; 999 | 1000 | // The OOP Wrapper 1001 | // --------------- 1002 | 1003 | // If Underscore is called as a function, it returns a wrapped object that 1004 | // can be used OO-style. This wrapper holds altered versions of all the 1005 | // underscore functions. Wrapped objects may be chained. 1006 | var wrapper = function(obj) { this._wrapped = obj; }; 1007 | 1008 | // Expose `wrapper.prototype` as `_.prototype` 1009 | _.prototype = wrapper.prototype; 1010 | 1011 | // Helper function to continue chaining intermediate results. 1012 | var result = function(obj, chain) { 1013 | return chain ? _(obj).chain() : obj; 1014 | }; 1015 | 1016 | // A method to easily add functions to the OOP wrapper. 1017 | var addToWrapper = function(name, func) { 1018 | wrapper.prototype[name] = function() { 1019 | var args = slice.call(arguments); 1020 | unshift.call(args, this._wrapped); 1021 | return result(func.apply(_, args), this._chain); 1022 | }; 1023 | }; 1024 | 1025 | // Add all of the Underscore functions to the wrapper object. 1026 | _.mixin(_); 1027 | 1028 | // Add all mutator Array functions to the wrapper. 1029 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 1030 | var method = ArrayProto[name]; 1031 | wrapper.prototype[name] = function() { 1032 | var wrapped = this._wrapped; 1033 | method.apply(wrapped, arguments); 1034 | var length = wrapped.length; 1035 | if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0]; 1036 | return result(wrapped, this._chain); 1037 | }; 1038 | }); 1039 | 1040 | // Add all accessor Array functions to the wrapper. 1041 | each(['concat', 'join', 'slice'], function(name) { 1042 | var method = ArrayProto[name]; 1043 | wrapper.prototype[name] = function() { 1044 | return result(method.apply(this._wrapped, arguments), this._chain); 1045 | }; 1046 | }); 1047 | 1048 | // Start chaining a wrapped Underscore object. 1049 | wrapper.prototype.chain = function() { 1050 | this._chain = true; 1051 | return this; 1052 | }; 1053 | 1054 | // Extracts the result from a wrapped and chained object. 1055 | wrapper.prototype.value = function() { 1056 | return this._wrapped; 1057 | }; 1058 | 1059 | }).call(this); 1060 | -------------------------------------------------------------------------------- /demo/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 `"key", value` and `{key: value}` -style arguments. 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.comparator) this.comparator = options.comparator; 562 | this._reset(); 563 | this.initialize.apply(this, arguments); 564 | if (models) this.reset(models, {silent: true, parse: options.parse}); 565 | }; 566 | 567 | // Define the Collection's inheritable methods. 568 | _.extend(Collection.prototype, Events, { 569 | 570 | // The default model for a collection is just a **Backbone.Model**. 571 | // This should be overridden in most cases. 572 | model: Model, 573 | 574 | // Initialize is an empty function by default. Override it with your own 575 | // initialization logic. 576 | initialize: function(){}, 577 | 578 | // The JSON representation of a Collection is an array of the 579 | // models' attributes. 580 | toJSON: function(options) { 581 | return this.map(function(model){ return model.toJSON(options); }); 582 | }, 583 | 584 | // Add a model, or list of models to the set. Pass **silent** to avoid 585 | // firing the `add` event for every new model. 586 | add: function(models, options) { 587 | var i, index, length, model, cid, id, cids = {}, ids = {}, dups = []; 588 | options || (options = {}); 589 | models = _.isArray(models) ? models.slice() : [models]; 590 | 591 | // Begin by turning bare objects into model references, and preventing 592 | // invalid models or duplicate models from being added. 593 | for (i = 0, length = models.length; i < length; i++) { 594 | if (!(model = models[i] = this._prepareModel(models[i], options))) { 595 | throw new Error("Can't add an invalid model to a collection"); 596 | } 597 | cid = model.cid; 598 | id = model.id; 599 | if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) { 600 | dups.push(i); 601 | continue; 602 | } 603 | cids[cid] = ids[id] = model; 604 | } 605 | 606 | // Remove duplicates. 607 | i = dups.length; 608 | while (i--) { 609 | models.splice(dups[i], 1); 610 | } 611 | 612 | // Listen to added models' events, and index models for lookup by 613 | // `id` and by `cid`. 614 | for (i = 0, length = models.length; i < length; i++) { 615 | (model = models[i]).on('all', this._onModelEvent, this); 616 | this._byCid[model.cid] = model; 617 | if (model.id != null) this._byId[model.id] = model; 618 | } 619 | 620 | // Insert models into the collection, re-sorting if needed, and triggering 621 | // `add` events unless silenced. 622 | this.length += length; 623 | index = options.at != null ? options.at : this.models.length; 624 | splice.apply(this.models, [index, 0].concat(models)); 625 | if (this.comparator) this.sort({silent: true}); 626 | if (options.silent) return this; 627 | for (i = 0, length = this.models.length; i < length; i++) { 628 | if (!cids[(model = this.models[i]).cid]) continue; 629 | options.index = i; 630 | model.trigger('add', model, this, options); 631 | } 632 | return this; 633 | }, 634 | 635 | // Remove a model, or a list of models from the set. Pass silent to avoid 636 | // firing the `remove` event for every model removed. 637 | remove: function(models, options) { 638 | var i, l, index, model; 639 | options || (options = {}); 640 | models = _.isArray(models) ? models.slice() : [models]; 641 | for (i = 0, l = models.length; i < l; i++) { 642 | model = this.getByCid(models[i]) || this.get(models[i]); 643 | if (!model) continue; 644 | delete this._byId[model.id]; 645 | delete this._byCid[model.cid]; 646 | index = this.indexOf(model); 647 | this.models.splice(index, 1); 648 | this.length--; 649 | if (!options.silent) { 650 | options.index = index; 651 | model.trigger('remove', model, this, options); 652 | } 653 | this._removeReference(model); 654 | } 655 | return this; 656 | }, 657 | 658 | // Add a model to the end of the collection. 659 | push: function(model, options) { 660 | model = this._prepareModel(model, options); 661 | this.add(model, options); 662 | return model; 663 | }, 664 | 665 | // Remove a model from the end of the collection. 666 | pop: function(options) { 667 | var model = this.at(this.length - 1); 668 | this.remove(model, options); 669 | return model; 670 | }, 671 | 672 | // Add a model to the beginning of the collection. 673 | unshift: function(model, options) { 674 | model = this._prepareModel(model, options); 675 | this.add(model, _.extend({at: 0}, options)); 676 | return model; 677 | }, 678 | 679 | // Remove a model from the beginning of the collection. 680 | shift: function(options) { 681 | var model = this.at(0); 682 | this.remove(model, options); 683 | return model; 684 | }, 685 | 686 | // Get a model from the set by id. 687 | get: function(id) { 688 | if (id == null) return void 0; 689 | return this._byId[id.id != null ? id.id : id]; 690 | }, 691 | 692 | // Get a model from the set by client id. 693 | getByCid: function(cid) { 694 | return cid && this._byCid[cid.cid || cid]; 695 | }, 696 | 697 | // Get the model at the given index. 698 | at: function(index) { 699 | return this.models[index]; 700 | }, 701 | 702 | // Return models with matching attributes. Useful for simple cases of `filter`. 703 | where: function(attrs) { 704 | if (_.isEmpty(attrs)) return []; 705 | return this.filter(function(model) { 706 | for (var key in attrs) { 707 | if (attrs[key] !== model.get(key)) return false; 708 | } 709 | return true; 710 | }); 711 | }, 712 | 713 | // Force the collection to re-sort itself. You don't need to call this under 714 | // normal circumstances, as the set will maintain sort order as each item 715 | // is added. 716 | sort: function(options) { 717 | options || (options = {}); 718 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); 719 | var boundComparator = _.bind(this.comparator, this); 720 | if (this.comparator.length == 1) { 721 | this.models = this.sortBy(boundComparator); 722 | } else { 723 | this.models.sort(boundComparator); 724 | } 725 | if (!options.silent) this.trigger('reset', this, options); 726 | return this; 727 | }, 728 | 729 | // Pluck an attribute from each model in the collection. 730 | pluck: function(attr) { 731 | return _.map(this.models, function(model){ return model.get(attr); }); 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 `add` or `remove` events. Fires `reset` when finished. 737 | reset: function(models, options) { 738 | models || (models = []); 739 | options || (options = {}); 740 | for (var i = 0, l = this.models.length; i < l; i++) { 741 | this._removeReference(this.models[i]); 742 | } 743 | this._reset(); 744 | this.add(models, _.extend({silent: true}, options)); 745 | if (!options.silent) this.trigger('reset', this, options); 746 | return this; 747 | }, 748 | 749 | // Fetch the default set of models for this collection, resetting the 750 | // collection when they arrive. If `add: true` is passed, appends the 751 | // models to the collection instead of resetting. 752 | fetch: function(options) { 753 | options = options ? _.clone(options) : {}; 754 | if (options.parse === undefined) options.parse = true; 755 | var collection = this; 756 | var success = options.success; 757 | options.success = function(resp, status, xhr) { 758 | collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options); 759 | if (success) success(collection, resp); 760 | }; 761 | options.error = Backbone.wrapError(options.error, collection, options); 762 | return (this.sync || Backbone.sync).call(this, 'read', this, options); 763 | }, 764 | 765 | // Create a new instance of a model in this collection. Add the model to the 766 | // collection immediately, unless `wait: true` is passed, in which case we 767 | // wait for the server to agree. 768 | create: function(model, options) { 769 | var coll = this; 770 | options = options ? _.clone(options) : {}; 771 | model = this._prepareModel(model, options); 772 | if (!model) return false; 773 | if (!options.wait) coll.add(model, options); 774 | var success = options.success; 775 | options.success = function(nextModel, resp, xhr) { 776 | if (options.wait) coll.add(nextModel, options); 777 | if (success) { 778 | success(nextModel, resp); 779 | } else { 780 | nextModel.trigger('sync', model, resp, options); 781 | } 782 | }; 783 | model.save(null, options); 784 | return model; 785 | }, 786 | 787 | // **parse** converts a response into a list of models to be added to the 788 | // collection. The default implementation is just to pass it through. 789 | parse: function(resp, xhr) { 790 | return resp; 791 | }, 792 | 793 | // Proxy to _'s chain. Can't be proxied the same way the rest of the 794 | // underscore methods are proxied because it relies on the underscore 795 | // constructor. 796 | chain: function () { 797 | return _(this.models).chain(); 798 | }, 799 | 800 | // Reset all internal state. Called when the collection is reset. 801 | _reset: function(options) { 802 | this.length = 0; 803 | this.models = []; 804 | this._byId = {}; 805 | this._byCid = {}; 806 | }, 807 | 808 | // Prepare a model or hash of attributes to be added to this collection. 809 | _prepareModel: function(model, options) { 810 | options || (options = {}); 811 | if (!(model instanceof Model)) { 812 | var attrs = model; 813 | options.collection = this; 814 | model = new this.model(attrs, options); 815 | if (!model._validate(model.attributes, options)) model = false; 816 | } else if (!model.collection) { 817 | model.collection = this; 818 | } 819 | return model; 820 | }, 821 | 822 | // Internal method to remove a model's ties to a collection. 823 | _removeReference: function(model) { 824 | if (this == model.collection) { 825 | delete model.collection; 826 | } 827 | model.off('all', this._onModelEvent, this); 828 | }, 829 | 830 | // Internal method called every time a model in the set fires an event. 831 | // Sets need to update their indexes when models change ids. All other 832 | // events simply proxy through. "add" and "remove" events that originate 833 | // in other collections are ignored. 834 | _onModelEvent: function(event, model, collection, options) { 835 | if ((event == 'add' || event == 'remove') && collection != this) return; 836 | if (event == 'destroy') { 837 | this.remove(model, options); 838 | } 839 | if (model && event === 'change:' + model.idAttribute) { 840 | delete this._byId[model.previous(model.idAttribute)]; 841 | this._byId[model.id] = model; 842 | } 843 | this.trigger.apply(this, arguments); 844 | } 845 | 846 | }); 847 | 848 | // Underscore methods that we want to implement on the Collection. 849 | var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 850 | 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 851 | 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 852 | 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', 853 | 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy']; 854 | 855 | // Mix in each Underscore method as a proxy to `Collection#models`. 856 | _.each(methods, function(method) { 857 | Collection.prototype[method] = function() { 858 | return _[method].apply(_, [this.models].concat(_.toArray(arguments))); 859 | }; 860 | }); 861 | 862 | // Backbone.Router 863 | // ------------------- 864 | 865 | // Routers map faux-URLs to actions, and fire events when routes are 866 | // matched. Creating a new one sets its `routes` hash, if not set statically. 867 | var Router = Backbone.Router = function(options) { 868 | options || (options = {}); 869 | if (options.routes) this.routes = options.routes; 870 | this._bindRoutes(); 871 | this.initialize.apply(this, arguments); 872 | }; 873 | 874 | // Cached regular expressions for matching named param parts and splatted 875 | // parts of route strings. 876 | var namedParam = /:\w+/g; 877 | var splatParam = /\*\w+/g; 878 | var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; 879 | 880 | // Set up all inheritable **Backbone.Router** properties and methods. 881 | _.extend(Router.prototype, Events, { 882 | 883 | // Initialize is an empty function by default. Override it with your own 884 | // initialization logic. 885 | initialize: function(){}, 886 | 887 | // Manually bind a single named route to a callback. For example: 888 | // 889 | // this.route('search/:query/p:num', 'search', function(query, num) { 890 | // ... 891 | // }); 892 | // 893 | route: function(route, name, callback) { 894 | Backbone.history || (Backbone.history = new History); 895 | if (!_.isRegExp(route)) route = this._routeToRegExp(route); 896 | if (!callback) callback = this[name]; 897 | Backbone.history.route(route, _.bind(function(fragment) { 898 | var args = this._extractParameters(route, fragment); 899 | callback && callback.apply(this, args); 900 | this.trigger.apply(this, ['route:' + name].concat(args)); 901 | Backbone.history.trigger('route', this, name, args); 902 | }, this)); 903 | return this; 904 | }, 905 | 906 | // Simple proxy to `Backbone.history` to save a fragment into the history. 907 | navigate: function(fragment, options) { 908 | Backbone.history.navigate(fragment, options); 909 | }, 910 | 911 | // Bind all defined routes to `Backbone.history`. We have to reverse the 912 | // order of the routes here to support behavior where the most general 913 | // routes can be defined at the bottom of the route map. 914 | _bindRoutes: function() { 915 | if (!this.routes) return; 916 | var routes = []; 917 | for (var route in this.routes) { 918 | routes.unshift([route, this.routes[route]]); 919 | } 920 | for (var i = 0, l = routes.length; i < l; i++) { 921 | this.route(routes[i][0], routes[i][1], this[routes[i][1]]); 922 | } 923 | }, 924 | 925 | // Convert a route string into a regular expression, suitable for matching 926 | // against the current location hash. 927 | _routeToRegExp: function(route) { 928 | route = route.replace(escapeRegExp, '\\$&') 929 | .replace(namedParam, '([^\/]+)') 930 | .replace(splatParam, '(.*?)'); 931 | return new RegExp('^' + route + '$'); 932 | }, 933 | 934 | // Given a route, and a URL fragment that it matches, return the array of 935 | // extracted parameters. 936 | _extractParameters: function(route, fragment) { 937 | return route.exec(fragment).slice(1); 938 | } 939 | 940 | }); 941 | 942 | // Backbone.History 943 | // ---------------- 944 | 945 | // Handles cross-browser history management, based on URL fragments. If the 946 | // browser does not support `onhashchange`, falls back to polling. 947 | var History = Backbone.History = function() { 948 | this.handlers = []; 949 | _.bindAll(this, 'checkUrl'); 950 | }; 951 | 952 | // Cached regex for cleaning leading hashes and slashes . 953 | var routeStripper = /^[#\/]/; 954 | 955 | // Cached regex for detecting MSIE. 956 | var isExplorer = /msie [\w.]+/; 957 | 958 | // Has the history handling already been started? 959 | History.started = false; 960 | 961 | // Set up all inheritable **Backbone.History** properties and methods. 962 | _.extend(History.prototype, Events, { 963 | 964 | // The default interval to poll for hash changes, if necessary, is 965 | // twenty times a second. 966 | interval: 50, 967 | 968 | // Gets the true hash value. Cannot use location.hash directly due to bug 969 | // in Firefox where location.hash will always be decoded. 970 | getHash: function(windowOverride) { 971 | var loc = windowOverride ? windowOverride.location : window.location; 972 | var match = loc.href.match(/#(.*)$/); 973 | return match ? match[1] : ''; 974 | }, 975 | 976 | // Get the cross-browser normalized URL fragment, either from the URL, 977 | // the hash, or the override. 978 | getFragment: function(fragment, forcePushState) { 979 | if (fragment == null) { 980 | if (this._hasPushState || forcePushState) { 981 | fragment = window.location.pathname; 982 | var search = window.location.search; 983 | if (search) fragment += search; 984 | } else { 985 | fragment = this.getHash(); 986 | } 987 | } 988 | if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); 989 | return fragment.replace(routeStripper, ''); 990 | }, 991 | 992 | // Start the hash change handling, returning `true` if the current URL matches 993 | // an existing route, and `false` otherwise. 994 | start: function(options) { 995 | if (History.started) throw new Error("Backbone.history has already been started"); 996 | History.started = true; 997 | 998 | // Figure out the initial configuration. Do we need an iframe? 999 | // Is pushState desired ... is it available? 1000 | this.options = _.extend({}, {root: '/'}, this.options, options); 1001 | this._wantsHashChange = this.options.hashChange !== false; 1002 | this._wantsPushState = !!this.options.pushState; 1003 | this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState); 1004 | var fragment = this.getFragment(); 1005 | var docMode = document.documentMode; 1006 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); 1007 | 1008 | if (oldIE) { 1009 | this.iframe = $('