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