Chris@0: // Backbone.js 1.2.3 Chris@0: Chris@0: // (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors Chris@0: // Backbone may be freely distributed under the MIT license. Chris@0: // For all details and documentation: Chris@0: // http://backbonejs.org Chris@0: Chris@0: (function(factory) { Chris@0: Chris@0: // Establish the root object, `window` (`self`) in the browser, or `global` on the server. Chris@0: // We use `self` instead of `window` for `WebWorker` support. Chris@0: var root = (typeof self == 'object' && self.self == self && self) || Chris@0: (typeof global == 'object' && global.global == global && global); Chris@0: Chris@0: // Set up Backbone appropriately for the environment. Start with AMD. Chris@0: if (typeof define === 'function' && define.amd) { Chris@0: define(['underscore', 'jquery', 'exports'], function(_, $, exports) { Chris@0: // Export global even in AMD case in case this script is loaded with Chris@0: // others that may still expect a global Backbone. Chris@0: root.Backbone = factory(root, exports, _, $); Chris@0: }); Chris@0: Chris@0: // Next for Node.js or CommonJS. jQuery may not be needed as a module. Chris@0: } else if (typeof exports !== 'undefined') { Chris@0: var _ = require('underscore'), $; Chris@0: try { $ = require('jquery'); } catch(e) {} Chris@0: factory(root, exports, _, $); Chris@0: Chris@0: // Finally, as a browser global. Chris@0: } else { Chris@0: root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); Chris@0: } Chris@0: Chris@0: }(function(root, Backbone, _, $) { Chris@0: Chris@0: // Initial Setup Chris@0: // ------------- Chris@0: Chris@0: // Save the previous value of the `Backbone` variable, so that it can be Chris@0: // restored later on, if `noConflict` is used. Chris@0: var previousBackbone = root.Backbone; Chris@0: Chris@0: // Create a local reference to a common array method we'll want to use later. Chris@0: var slice = Array.prototype.slice; Chris@0: Chris@0: // Current version of the library. Keep in sync with `package.json`. Chris@0: Backbone.VERSION = '1.2.3'; Chris@0: Chris@0: // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns Chris@0: // the `$` variable. Chris@0: Backbone.$ = $; Chris@0: Chris@0: // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable Chris@0: // to its previous owner. Returns a reference to this Backbone object. Chris@0: Backbone.noConflict = function() { Chris@0: root.Backbone = previousBackbone; Chris@0: return this; Chris@0: }; Chris@0: Chris@0: // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option Chris@0: // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and Chris@0: // set a `X-Http-Method-Override` header. Chris@0: Backbone.emulateHTTP = false; Chris@0: Chris@0: // Turn on `emulateJSON` to support legacy servers that can't deal with direct Chris@0: // `application/json` requests ... this will encode the body as Chris@0: // `application/x-www-form-urlencoded` instead and will send the model in a Chris@0: // form param named `model`. Chris@0: Backbone.emulateJSON = false; Chris@0: Chris@0: // Proxy Backbone class methods to Underscore functions, wrapping the model's Chris@0: // `attributes` object or collection's `models` array behind the scenes. Chris@0: // Chris@0: // collection.filter(function(model) { return model.get('age') > 10 }); Chris@0: // collection.each(this.addView); Chris@0: // Chris@0: // `Function#apply` can be slow so we use the method's arg count, if we know it. Chris@0: var addMethod = function(length, method, attribute) { Chris@0: switch (length) { Chris@0: case 1: return function() { Chris@0: return _[method](this[attribute]); Chris@0: }; Chris@0: case 2: return function(value) { Chris@0: return _[method](this[attribute], value); Chris@0: }; Chris@0: case 3: return function(iteratee, context) { Chris@0: return _[method](this[attribute], cb(iteratee, this), context); Chris@0: }; Chris@0: case 4: return function(iteratee, defaultVal, context) { Chris@0: return _[method](this[attribute], cb(iteratee, this), defaultVal, context); Chris@0: }; Chris@0: default: return function() { Chris@0: var args = slice.call(arguments); Chris@0: args.unshift(this[attribute]); Chris@0: return _[method].apply(_, args); Chris@0: }; Chris@0: } Chris@0: }; Chris@0: var addUnderscoreMethods = function(Class, methods, attribute) { Chris@0: _.each(methods, function(length, method) { Chris@0: if (_[method]) Class.prototype[method] = addMethod(length, method, attribute); Chris@0: }); Chris@0: }; Chris@0: Chris@0: // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`. Chris@0: var cb = function(iteratee, instance) { Chris@0: if (_.isFunction(iteratee)) return iteratee; Chris@0: if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee); Chris@0: if (_.isString(iteratee)) return function(model) { return model.get(iteratee); }; Chris@0: return iteratee; Chris@0: }; Chris@0: var modelMatcher = function(attrs) { Chris@0: var matcher = _.matches(attrs); Chris@0: return function(model) { Chris@0: return matcher(model.attributes); Chris@0: }; Chris@0: }; Chris@0: Chris@0: // Backbone.Events Chris@0: // --------------- Chris@0: Chris@0: // A module that can be mixed in to *any object* in order to provide it with Chris@0: // a custom event channel. You may bind a callback to an event with `on` or Chris@0: // remove with `off`; `trigger`-ing an event fires all callbacks in Chris@0: // succession. Chris@0: // Chris@0: // var object = {}; Chris@0: // _.extend(object, Backbone.Events); Chris@0: // object.on('expand', function(){ alert('expanded'); }); Chris@0: // object.trigger('expand'); Chris@0: // Chris@0: var Events = Backbone.Events = {}; Chris@0: Chris@0: // Regular expression used to split event strings. Chris@0: var eventSplitter = /\s+/; Chris@0: Chris@0: // Iterates over the standard `event, callback` (as well as the fancy multiple Chris@0: // space-separated events `"change blur", callback` and jQuery-style event Chris@0: // maps `{event: callback}`). Chris@0: var eventsApi = function(iteratee, events, name, callback, opts) { Chris@0: var i = 0, names; Chris@0: if (name && typeof name === 'object') { Chris@0: // Handle event maps. Chris@0: if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback; Chris@0: for (names = _.keys(name); i < names.length ; i++) { Chris@0: events = eventsApi(iteratee, events, names[i], name[names[i]], opts); Chris@0: } Chris@0: } else if (name && eventSplitter.test(name)) { Chris@0: // Handle space separated event names by delegating them individually. Chris@0: for (names = name.split(eventSplitter); i < names.length; i++) { Chris@0: events = iteratee(events, names[i], callback, opts); Chris@0: } Chris@0: } else { Chris@0: // Finally, standard events. Chris@0: events = iteratee(events, name, callback, opts); Chris@0: } Chris@0: return events; Chris@0: }; Chris@0: Chris@0: // Bind an event to a `callback` function. Passing `"all"` will bind Chris@0: // the callback to all events fired. Chris@0: Events.on = function(name, callback, context) { Chris@0: return internalOn(this, name, callback, context); Chris@0: }; Chris@0: Chris@0: // Guard the `listening` argument from the public API. Chris@0: var internalOn = function(obj, name, callback, context, listening) { Chris@0: obj._events = eventsApi(onApi, obj._events || {}, name, callback, { Chris@0: context: context, Chris@0: ctx: obj, Chris@0: listening: listening Chris@0: }); Chris@0: Chris@0: if (listening) { Chris@0: var listeners = obj._listeners || (obj._listeners = {}); Chris@0: listeners[listening.id] = listening; Chris@0: } Chris@0: Chris@0: return obj; Chris@0: }; Chris@0: Chris@0: // Inversion-of-control versions of `on`. Tell *this* object to listen to Chris@0: // an event in another object... keeping track of what it's listening to Chris@0: // for easier unbinding later. Chris@0: Events.listenTo = function(obj, name, callback) { Chris@0: if (!obj) return this; Chris@0: var id = obj._listenId || (obj._listenId = _.uniqueId('l')); Chris@0: var listeningTo = this._listeningTo || (this._listeningTo = {}); Chris@0: var listening = listeningTo[id]; Chris@0: Chris@0: // This object is not listening to any other events on `obj` yet. Chris@0: // Setup the necessary references to track the listening callbacks. Chris@0: if (!listening) { Chris@0: var thisId = this._listenId || (this._listenId = _.uniqueId('l')); Chris@0: listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0}; Chris@0: } Chris@0: Chris@0: // Bind callbacks on obj, and keep track of them on listening. Chris@0: internalOn(obj, name, callback, this, listening); Chris@0: return this; Chris@0: }; Chris@0: Chris@0: // The reducing API that adds a callback to the `events` object. Chris@0: var onApi = function(events, name, callback, options) { Chris@0: if (callback) { Chris@0: var handlers = events[name] || (events[name] = []); Chris@0: var context = options.context, ctx = options.ctx, listening = options.listening; Chris@0: if (listening) listening.count++; Chris@0: Chris@0: handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening }); Chris@0: } Chris@0: return events; Chris@0: }; Chris@0: Chris@0: // Remove one or many callbacks. If `context` is null, removes all Chris@0: // callbacks with that function. If `callback` is null, removes all Chris@0: // callbacks for the event. If `name` is null, removes all bound Chris@0: // callbacks for all events. Chris@0: Events.off = function(name, callback, context) { Chris@0: if (!this._events) return this; Chris@0: this._events = eventsApi(offApi, this._events, name, callback, { Chris@0: context: context, Chris@0: listeners: this._listeners Chris@0: }); Chris@0: return this; Chris@0: }; Chris@0: Chris@0: // Tell this object to stop listening to either specific events ... or Chris@0: // to every object it's currently listening to. Chris@0: Events.stopListening = function(obj, name, callback) { Chris@0: var listeningTo = this._listeningTo; Chris@0: if (!listeningTo) return this; Chris@0: Chris@0: var ids = obj ? [obj._listenId] : _.keys(listeningTo); Chris@0: Chris@0: for (var i = 0; i < ids.length; i++) { Chris@0: var listening = listeningTo[ids[i]]; Chris@0: Chris@0: // If listening doesn't exist, this object is not currently Chris@0: // listening to obj. Break out early. Chris@0: if (!listening) break; Chris@0: Chris@0: listening.obj.off(name, callback, this); Chris@0: } Chris@0: if (_.isEmpty(listeningTo)) this._listeningTo = void 0; Chris@0: Chris@0: return this; Chris@0: }; Chris@0: Chris@0: // The reducing API that removes a callback from the `events` object. Chris@0: var offApi = function(events, name, callback, options) { Chris@0: if (!events) return; Chris@0: Chris@0: var i = 0, listening; Chris@0: var context = options.context, listeners = options.listeners; Chris@0: Chris@0: // Delete all events listeners and "drop" events. Chris@0: if (!name && !callback && !context) { Chris@0: var ids = _.keys(listeners); Chris@0: for (; i < ids.length; i++) { Chris@0: listening = listeners[ids[i]]; Chris@0: delete listeners[listening.id]; Chris@0: delete listening.listeningTo[listening.objId]; Chris@0: } Chris@0: return; Chris@0: } Chris@0: Chris@0: var names = name ? [name] : _.keys(events); Chris@0: for (; i < names.length; i++) { Chris@0: name = names[i]; Chris@0: var handlers = events[name]; Chris@0: Chris@0: // Bail out if there are no events stored. Chris@0: if (!handlers) break; Chris@0: Chris@0: // Replace events if there are any remaining. Otherwise, clean up. Chris@0: var remaining = []; Chris@0: for (var j = 0; j < handlers.length; j++) { Chris@0: var handler = handlers[j]; Chris@0: if ( Chris@0: callback && callback !== handler.callback && Chris@0: callback !== handler.callback._callback || Chris@0: context && context !== handler.context Chris@0: ) { Chris@0: remaining.push(handler); Chris@0: } else { Chris@0: listening = handler.listening; Chris@0: if (listening && --listening.count === 0) { Chris@0: delete listeners[listening.id]; Chris@0: delete listening.listeningTo[listening.objId]; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Update tail event if the list has any events. Otherwise, clean up. Chris@0: if (remaining.length) { Chris@0: events[name] = remaining; Chris@0: } else { Chris@0: delete events[name]; Chris@0: } Chris@0: } Chris@0: if (_.size(events)) return events; Chris@0: }; Chris@0: Chris@0: // Bind an event to only be triggered a single time. After the first time Chris@0: // the callback is invoked, its listener will be removed. If multiple events Chris@0: // are passed in using the space-separated syntax, the handler will fire Chris@0: // once for each event, not once for a combination of all events. Chris@0: Events.once = function(name, callback, context) { Chris@0: // Map the event into a `{event: once}` object. Chris@0: var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this)); Chris@0: return this.on(events, void 0, context); Chris@0: }; Chris@0: Chris@0: // Inversion-of-control versions of `once`. Chris@0: Events.listenToOnce = function(obj, name, callback) { Chris@0: // Map the event into a `{event: once}` object. Chris@0: var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj)); Chris@0: return this.listenTo(obj, events); Chris@0: }; Chris@0: Chris@0: // Reduces the event callbacks into a map of `{event: onceWrapper}`. Chris@0: // `offer` unbinds the `onceWrapper` after it has been called. Chris@0: var onceMap = function(map, name, callback, offer) { Chris@0: if (callback) { Chris@0: var once = map[name] = _.once(function() { Chris@0: offer(name, once); Chris@0: callback.apply(this, arguments); Chris@0: }); Chris@0: once._callback = callback; Chris@0: } Chris@0: return map; Chris@0: }; Chris@0: Chris@0: // Trigger one or many events, firing all bound callbacks. Callbacks are Chris@0: // passed the same arguments as `trigger` is, apart from the event name Chris@0: // (unless you're listening on `"all"`, which will cause your callback to Chris@0: // receive the true name of the event as the first argument). Chris@0: Events.trigger = function(name) { Chris@0: if (!this._events) return this; Chris@0: Chris@0: var length = Math.max(0, arguments.length - 1); Chris@0: var args = Array(length); Chris@0: for (var i = 0; i < length; i++) args[i] = arguments[i + 1]; Chris@0: Chris@0: eventsApi(triggerApi, this._events, name, void 0, args); Chris@0: return this; Chris@0: }; Chris@0: Chris@0: // Handles triggering the appropriate event callbacks. Chris@0: var triggerApi = function(objEvents, name, cb, args) { Chris@0: if (objEvents) { Chris@0: var events = objEvents[name]; Chris@0: var allEvents = objEvents.all; Chris@0: if (events && allEvents) allEvents = allEvents.slice(); Chris@0: if (events) triggerEvents(events, args); Chris@0: if (allEvents) triggerEvents(allEvents, [name].concat(args)); Chris@0: } Chris@0: return objEvents; Chris@0: }; Chris@0: Chris@0: // A difficult-to-believe, but optimized internal dispatch function for Chris@0: // triggering events. Tries to keep the usual cases speedy (most internal Chris@0: // Backbone events have 3 arguments). Chris@0: var triggerEvents = function(events, args) { Chris@0: var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; Chris@0: switch (args.length) { Chris@0: case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; Chris@0: case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; Chris@0: case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; Chris@0: case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; Chris@0: default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; Chris@0: } Chris@0: }; Chris@0: Chris@0: // Aliases for backwards compatibility. Chris@0: Events.bind = Events.on; Chris@0: Events.unbind = Events.off; Chris@0: Chris@0: // Allow the `Backbone` object to serve as a global event bus, for folks who Chris@0: // want global "pubsub" in a convenient place. Chris@0: _.extend(Backbone, Events); Chris@0: Chris@0: // Backbone.Model Chris@0: // -------------- Chris@0: Chris@0: // Backbone **Models** are the basic data object in the framework -- Chris@0: // frequently representing a row in a table in a database on your server. Chris@0: // A discrete chunk of data and a bunch of useful, related methods for Chris@0: // performing computations and transformations on that data. Chris@0: Chris@0: // Create a new model with the specified attributes. A client id (`cid`) Chris@0: // is automatically generated and assigned for you. Chris@0: var Model = Backbone.Model = function(attributes, options) { Chris@0: var attrs = attributes || {}; Chris@0: options || (options = {}); Chris@0: this.cid = _.uniqueId(this.cidPrefix); Chris@0: this.attributes = {}; Chris@0: if (options.collection) this.collection = options.collection; Chris@0: if (options.parse) attrs = this.parse(attrs, options) || {}; Chris@0: attrs = _.defaults({}, attrs, _.result(this, 'defaults')); Chris@0: this.set(attrs, options); Chris@0: this.changed = {}; Chris@0: this.initialize.apply(this, arguments); Chris@0: }; Chris@0: Chris@0: // Attach all inheritable methods to the Model prototype. Chris@0: _.extend(Model.prototype, Events, { Chris@0: Chris@0: // A hash of attributes whose current and previous value differ. Chris@0: changed: null, Chris@0: Chris@0: // The value returned during the last failed validation. Chris@0: validationError: null, Chris@0: Chris@0: // The default name for the JSON `id` attribute is `"id"`. MongoDB and Chris@0: // CouchDB users may want to set this to `"_id"`. Chris@0: idAttribute: 'id', Chris@0: Chris@0: // The prefix is used to create the client id which is used to identify models locally. Chris@0: // You may want to override this if you're experiencing name clashes with model ids. Chris@0: cidPrefix: 'c', Chris@0: Chris@0: // Initialize is an empty function by default. Override it with your own Chris@0: // initialization logic. Chris@0: initialize: function(){}, Chris@0: Chris@0: // Return a copy of the model's `attributes` object. Chris@0: toJSON: function(options) { Chris@0: return _.clone(this.attributes); Chris@0: }, Chris@0: Chris@0: // Proxy `Backbone.sync` by default -- but override this if you need Chris@0: // custom syncing semantics for *this* particular model. Chris@0: sync: function() { Chris@0: return Backbone.sync.apply(this, arguments); Chris@0: }, Chris@0: Chris@0: // Get the value of an attribute. Chris@0: get: function(attr) { Chris@0: return this.attributes[attr]; Chris@0: }, Chris@0: Chris@0: // Get the HTML-escaped value of an attribute. Chris@0: escape: function(attr) { Chris@0: return _.escape(this.get(attr)); Chris@0: }, Chris@0: Chris@0: // Returns `true` if the attribute contains a value that is not null Chris@0: // or undefined. Chris@0: has: function(attr) { Chris@0: return this.get(attr) != null; Chris@0: }, Chris@0: Chris@0: // Special-cased proxy to underscore's `_.matches` method. Chris@0: matches: function(attrs) { Chris@0: return !!_.iteratee(attrs, this)(this.attributes); Chris@0: }, Chris@0: Chris@0: // Set a hash of model attributes on the object, firing `"change"`. This is Chris@0: // the core primitive operation of a model, updating the data and notifying Chris@0: // anyone who needs to know about the change in state. The heart of the beast. Chris@0: set: function(key, val, options) { Chris@0: if (key == null) return this; Chris@0: Chris@0: // Handle both `"key", value` and `{key: value}` -style arguments. Chris@0: var attrs; Chris@0: if (typeof key === 'object') { Chris@0: attrs = key; Chris@0: options = val; Chris@0: } else { Chris@0: (attrs = {})[key] = val; Chris@0: } Chris@0: Chris@0: options || (options = {}); Chris@0: Chris@0: // Run validation. Chris@0: if (!this._validate(attrs, options)) return false; Chris@0: Chris@0: // Extract attributes and options. Chris@0: var unset = options.unset; Chris@0: var silent = options.silent; Chris@0: var changes = []; Chris@0: var changing = this._changing; Chris@0: this._changing = true; Chris@0: Chris@0: if (!changing) { Chris@0: this._previousAttributes = _.clone(this.attributes); Chris@0: this.changed = {}; Chris@0: } Chris@0: Chris@0: var current = this.attributes; Chris@0: var changed = this.changed; Chris@0: var prev = this._previousAttributes; Chris@0: Chris@0: // For each `set` attribute, update or delete the current value. Chris@0: for (var attr in attrs) { Chris@0: val = attrs[attr]; Chris@0: if (!_.isEqual(current[attr], val)) changes.push(attr); Chris@0: if (!_.isEqual(prev[attr], val)) { Chris@0: changed[attr] = val; Chris@0: } else { Chris@0: delete changed[attr]; Chris@0: } Chris@0: unset ? delete current[attr] : current[attr] = val; Chris@0: } Chris@0: Chris@0: // Update the `id`. Chris@0: this.id = this.get(this.idAttribute); Chris@0: Chris@0: // Trigger all relevant attribute changes. Chris@0: if (!silent) { Chris@0: if (changes.length) this._pending = options; Chris@0: for (var i = 0; i < changes.length; i++) { Chris@0: this.trigger('change:' + changes[i], this, current[changes[i]], options); Chris@0: } Chris@0: } Chris@0: Chris@0: // You might be wondering why there's a `while` loop here. Changes can Chris@0: // be recursively nested within `"change"` events. Chris@0: if (changing) return this; Chris@0: if (!silent) { Chris@0: while (this._pending) { Chris@0: options = this._pending; Chris@0: this._pending = false; Chris@0: this.trigger('change', this, options); Chris@0: } Chris@0: } Chris@0: this._pending = false; Chris@0: this._changing = false; Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Remove an attribute from the model, firing `"change"`. `unset` is a noop Chris@0: // if the attribute doesn't exist. Chris@0: unset: function(attr, options) { Chris@0: return this.set(attr, void 0, _.extend({}, options, {unset: true})); Chris@0: }, Chris@0: Chris@0: // Clear all attributes on the model, firing `"change"`. Chris@0: clear: function(options) { Chris@0: var attrs = {}; Chris@0: for (var key in this.attributes) attrs[key] = void 0; Chris@0: return this.set(attrs, _.extend({}, options, {unset: true})); Chris@0: }, Chris@0: Chris@0: // Determine if the model has changed since the last `"change"` event. Chris@0: // If you specify an attribute name, determine if that attribute has changed. Chris@0: hasChanged: function(attr) { Chris@0: if (attr == null) return !_.isEmpty(this.changed); Chris@0: return _.has(this.changed, attr); Chris@0: }, Chris@0: Chris@0: // Return an object containing all the attributes that have changed, or Chris@0: // false if there are no changed attributes. Useful for determining what Chris@0: // parts of a view need to be updated and/or what attributes need to be Chris@0: // persisted to the server. Unset attributes will be set to undefined. Chris@0: // You can also pass an attributes object to diff against the model, Chris@0: // determining if there *would be* a change. Chris@0: changedAttributes: function(diff) { Chris@0: if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; Chris@0: var old = this._changing ? this._previousAttributes : this.attributes; Chris@0: var changed = {}; Chris@0: for (var attr in diff) { Chris@0: var val = diff[attr]; Chris@0: if (_.isEqual(old[attr], val)) continue; Chris@0: changed[attr] = val; Chris@0: } Chris@0: return _.size(changed) ? changed : false; Chris@0: }, Chris@0: Chris@0: // Get the previous value of an attribute, recorded at the time the last Chris@0: // `"change"` event was fired. Chris@0: previous: function(attr) { Chris@0: if (attr == null || !this._previousAttributes) return null; Chris@0: return this._previousAttributes[attr]; Chris@0: }, Chris@0: Chris@0: // Get all of the attributes of the model at the time of the previous Chris@0: // `"change"` event. Chris@0: previousAttributes: function() { Chris@0: return _.clone(this._previousAttributes); Chris@0: }, Chris@0: Chris@0: // Fetch the model from the server, merging the response with the model's Chris@0: // local attributes. Any changed attributes will trigger a "change" event. Chris@0: fetch: function(options) { Chris@0: options = _.extend({parse: true}, options); Chris@0: var model = this; Chris@0: var success = options.success; Chris@0: options.success = function(resp) { Chris@0: var serverAttrs = options.parse ? model.parse(resp, options) : resp; Chris@0: if (!model.set(serverAttrs, options)) return false; Chris@0: if (success) success.call(options.context, model, resp, options); Chris@0: model.trigger('sync', model, resp, options); Chris@0: }; Chris@0: wrapError(this, options); Chris@0: return this.sync('read', this, options); Chris@0: }, Chris@0: Chris@0: // Set a hash of model attributes, and sync the model to the server. Chris@0: // If the server returns an attributes hash that differs, the model's Chris@0: // state will be `set` again. Chris@0: save: function(key, val, options) { Chris@0: // Handle both `"key", value` and `{key: value}` -style arguments. Chris@0: var attrs; Chris@0: if (key == null || typeof key === 'object') { Chris@0: attrs = key; Chris@0: options = val; Chris@0: } else { Chris@0: (attrs = {})[key] = val; Chris@0: } Chris@0: Chris@0: options = _.extend({validate: true, parse: true}, options); Chris@0: var wait = options.wait; Chris@0: Chris@0: // If we're not waiting and attributes exist, save acts as Chris@0: // `set(attr).save(null, opts)` with validation. Otherwise, check if Chris@0: // the model will be valid when the attributes, if any, are set. Chris@0: if (attrs && !wait) { Chris@0: if (!this.set(attrs, options)) return false; Chris@0: } else { Chris@0: if (!this._validate(attrs, options)) return false; Chris@0: } Chris@0: Chris@0: // After a successful server-side save, the client is (optionally) Chris@0: // updated with the server-side state. Chris@0: var model = this; Chris@0: var success = options.success; Chris@0: var attributes = this.attributes; Chris@0: options.success = function(resp) { Chris@0: // Ensure attributes are restored during synchronous saves. Chris@0: model.attributes = attributes; Chris@0: var serverAttrs = options.parse ? model.parse(resp, options) : resp; Chris@0: if (wait) serverAttrs = _.extend({}, attrs, serverAttrs); Chris@0: if (serverAttrs && !model.set(serverAttrs, options)) return false; Chris@0: if (success) success.call(options.context, model, resp, options); Chris@0: model.trigger('sync', model, resp, options); Chris@0: }; Chris@0: wrapError(this, options); Chris@0: Chris@0: // Set temporary attributes if `{wait: true}` to properly find new ids. Chris@0: if (attrs && wait) this.attributes = _.extend({}, attributes, attrs); Chris@0: Chris@0: var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); Chris@0: if (method === 'patch' && !options.attrs) options.attrs = attrs; Chris@0: var xhr = this.sync(method, this, options); Chris@0: Chris@0: // Restore attributes. Chris@0: this.attributes = attributes; Chris@0: Chris@0: return xhr; Chris@0: }, Chris@0: Chris@0: // Destroy this model on the server if it was already persisted. Chris@0: // Optimistically removes the model from its collection, if it has one. Chris@0: // If `wait: true` is passed, waits for the server to respond before removal. Chris@0: destroy: function(options) { Chris@0: options = options ? _.clone(options) : {}; Chris@0: var model = this; Chris@0: var success = options.success; Chris@0: var wait = options.wait; Chris@0: Chris@0: var destroy = function() { Chris@0: model.stopListening(); Chris@0: model.trigger('destroy', model, model.collection, options); Chris@0: }; Chris@0: Chris@0: options.success = function(resp) { Chris@0: if (wait) destroy(); Chris@0: if (success) success.call(options.context, model, resp, options); Chris@0: if (!model.isNew()) model.trigger('sync', model, resp, options); Chris@0: }; Chris@0: Chris@0: var xhr = false; Chris@0: if (this.isNew()) { Chris@0: _.defer(options.success); Chris@0: } else { Chris@0: wrapError(this, options); Chris@0: xhr = this.sync('delete', this, options); Chris@0: } Chris@0: if (!wait) destroy(); Chris@0: return xhr; Chris@0: }, Chris@0: Chris@0: // Default URL for the model's representation on the server -- if you're Chris@0: // using Backbone's restful methods, override this to change the endpoint Chris@0: // that will be called. Chris@0: url: function() { Chris@0: var base = Chris@0: _.result(this, 'urlRoot') || Chris@0: _.result(this.collection, 'url') || Chris@0: urlError(); Chris@0: if (this.isNew()) return base; Chris@0: var id = this.get(this.idAttribute); Chris@0: return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); Chris@0: }, Chris@0: Chris@0: // **parse** converts a response into the hash of attributes to be `set` on Chris@0: // the model. The default implementation is just to pass the response along. Chris@0: parse: function(resp, options) { Chris@0: return resp; Chris@0: }, Chris@0: Chris@0: // Create a new model with identical attributes to this one. Chris@0: clone: function() { Chris@0: return new this.constructor(this.attributes); Chris@0: }, Chris@0: Chris@0: // A model is new if it has never been saved to the server, and lacks an id. Chris@0: isNew: function() { Chris@0: return !this.has(this.idAttribute); Chris@0: }, Chris@0: Chris@0: // Check if the model is currently in a valid state. Chris@0: isValid: function(options) { Chris@0: return this._validate({}, _.defaults({validate: true}, options)); Chris@0: }, Chris@0: Chris@0: // Run validation against the next complete set of model attributes, Chris@0: // returning `true` if all is well. Otherwise, fire an `"invalid"` event. Chris@0: _validate: function(attrs, options) { Chris@0: if (!options.validate || !this.validate) return true; Chris@0: attrs = _.extend({}, this.attributes, attrs); Chris@0: var error = this.validationError = this.validate(attrs, options) || null; Chris@0: if (!error) return true; Chris@0: this.trigger('invalid', this, error, _.extend(options, {validationError: error})); Chris@0: return false; Chris@0: } Chris@0: Chris@0: }); Chris@0: Chris@0: // Underscore methods that we want to implement on the Model, mapped to the Chris@0: // number of arguments they take. Chris@0: var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0, Chris@0: omit: 0, chain: 1, isEmpty: 1 }; Chris@0: Chris@0: // Mix in each Underscore method as a proxy to `Model#attributes`. Chris@0: addUnderscoreMethods(Model, modelMethods, 'attributes'); Chris@0: Chris@0: // Backbone.Collection Chris@0: // ------------------- Chris@0: Chris@0: // If models tend to represent a single row of data, a Backbone Collection is Chris@0: // more analogous to a table full of data ... or a small slice or page of that Chris@0: // table, or a collection of rows that belong together for a particular reason Chris@0: // -- all of the messages in this particular folder, all of the documents Chris@0: // belonging to this particular author, and so on. Collections maintain Chris@0: // indexes of their models, both in order, and for lookup by `id`. Chris@0: Chris@0: // Create a new **Collection**, perhaps to contain a specific type of `model`. Chris@0: // If a `comparator` is specified, the Collection will maintain Chris@0: // its models in sort order, as they're added and removed. Chris@0: var Collection = Backbone.Collection = function(models, options) { Chris@0: options || (options = {}); Chris@0: if (options.model) this.model = options.model; Chris@0: if (options.comparator !== void 0) this.comparator = options.comparator; Chris@0: this._reset(); Chris@0: this.initialize.apply(this, arguments); Chris@0: if (models) this.reset(models, _.extend({silent: true}, options)); Chris@0: }; Chris@0: Chris@0: // Default options for `Collection#set`. Chris@0: var setOptions = {add: true, remove: true, merge: true}; Chris@0: var addOptions = {add: true, remove: false}; Chris@0: Chris@0: // Splices `insert` into `array` at index `at`. Chris@0: var splice = function(array, insert, at) { Chris@0: at = Math.min(Math.max(at, 0), array.length); Chris@0: var tail = Array(array.length - at); Chris@0: var length = insert.length; Chris@0: for (var i = 0; i < tail.length; i++) tail[i] = array[i + at]; Chris@0: for (i = 0; i < length; i++) array[i + at] = insert[i]; Chris@0: for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i]; Chris@0: }; Chris@0: Chris@0: // Define the Collection's inheritable methods. Chris@0: _.extend(Collection.prototype, Events, { Chris@0: Chris@0: // The default model for a collection is just a **Backbone.Model**. Chris@0: // This should be overridden in most cases. Chris@0: model: Model, Chris@0: Chris@0: // Initialize is an empty function by default. Override it with your own Chris@0: // initialization logic. Chris@0: initialize: function(){}, Chris@0: Chris@0: // The JSON representation of a Collection is an array of the Chris@0: // models' attributes. Chris@0: toJSON: function(options) { Chris@0: return this.map(function(model) { return model.toJSON(options); }); Chris@0: }, Chris@0: Chris@0: // Proxy `Backbone.sync` by default. Chris@0: sync: function() { Chris@0: return Backbone.sync.apply(this, arguments); Chris@0: }, Chris@0: Chris@0: // Add a model, or list of models to the set. `models` may be Backbone Chris@0: // Models or raw JavaScript objects to be converted to Models, or any Chris@0: // combination of the two. Chris@0: add: function(models, options) { Chris@0: return this.set(models, _.extend({merge: false}, options, addOptions)); Chris@0: }, Chris@0: Chris@0: // Remove a model, or a list of models from the set. Chris@0: remove: function(models, options) { Chris@0: options = _.extend({}, options); Chris@0: var singular = !_.isArray(models); Chris@0: models = singular ? [models] : _.clone(models); Chris@0: var removed = this._removeModels(models, options); Chris@0: if (!options.silent && removed) this.trigger('update', this, options); Chris@0: return singular ? removed[0] : removed; Chris@0: }, Chris@0: Chris@0: // Update a collection by `set`-ing a new list of models, adding new ones, Chris@0: // removing models that are no longer present, and merging models that Chris@0: // already exist in the collection, as necessary. Similar to **Model#set**, Chris@0: // the core operation for updating the data contained by the collection. Chris@0: set: function(models, options) { Chris@0: if (models == null) return; Chris@0: Chris@0: options = _.defaults({}, options, setOptions); Chris@0: if (options.parse && !this._isModel(models)) models = this.parse(models, options); Chris@0: Chris@0: var singular = !_.isArray(models); Chris@0: models = singular ? [models] : models.slice(); Chris@0: Chris@0: var at = options.at; Chris@0: if (at != null) at = +at; Chris@0: if (at < 0) at += this.length + 1; Chris@0: Chris@0: var set = []; Chris@0: var toAdd = []; Chris@0: var toRemove = []; Chris@0: var modelMap = {}; Chris@0: Chris@0: var add = options.add; Chris@0: var merge = options.merge; Chris@0: var remove = options.remove; Chris@0: Chris@0: var sort = false; Chris@0: var sortable = this.comparator && (at == null) && options.sort !== false; Chris@0: var sortAttr = _.isString(this.comparator) ? this.comparator : null; Chris@0: Chris@0: // Turn bare objects into model references, and prevent invalid models Chris@0: // from being added. Chris@0: var model; Chris@0: for (var i = 0; i < models.length; i++) { Chris@0: model = models[i]; Chris@0: Chris@0: // If a duplicate is found, prevent it from being added and Chris@0: // optionally merge it into the existing model. Chris@0: var existing = this.get(model); Chris@0: if (existing) { Chris@0: if (merge && model !== existing) { Chris@0: var attrs = this._isModel(model) ? model.attributes : model; Chris@0: if (options.parse) attrs = existing.parse(attrs, options); Chris@0: existing.set(attrs, options); Chris@0: if (sortable && !sort) sort = existing.hasChanged(sortAttr); Chris@0: } Chris@0: if (!modelMap[existing.cid]) { Chris@0: modelMap[existing.cid] = true; Chris@0: set.push(existing); Chris@0: } Chris@0: models[i] = existing; Chris@0: Chris@0: // If this is a new, valid model, push it to the `toAdd` list. Chris@0: } else if (add) { Chris@0: model = models[i] = this._prepareModel(model, options); Chris@0: if (model) { Chris@0: toAdd.push(model); Chris@0: this._addReference(model, options); Chris@0: modelMap[model.cid] = true; Chris@0: set.push(model); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: // Remove stale models. Chris@0: if (remove) { Chris@0: for (i = 0; i < this.length; i++) { Chris@0: model = this.models[i]; Chris@0: if (!modelMap[model.cid]) toRemove.push(model); Chris@0: } Chris@0: if (toRemove.length) this._removeModels(toRemove, options); Chris@0: } Chris@0: Chris@0: // See if sorting is needed, update `length` and splice in new models. Chris@0: var orderChanged = false; Chris@0: var replace = !sortable && add && remove; Chris@0: if (set.length && replace) { Chris@0: orderChanged = this.length != set.length || _.some(this.models, function(model, index) { Chris@0: return model !== set[index]; Chris@0: }); Chris@0: this.models.length = 0; Chris@0: splice(this.models, set, 0); Chris@0: this.length = this.models.length; Chris@0: } else if (toAdd.length) { Chris@0: if (sortable) sort = true; Chris@0: splice(this.models, toAdd, at == null ? this.length : at); Chris@0: this.length = this.models.length; Chris@0: } Chris@0: Chris@0: // Silently sort the collection if appropriate. Chris@0: if (sort) this.sort({silent: true}); Chris@0: Chris@0: // Unless silenced, it's time to fire all appropriate add/sort events. Chris@0: if (!options.silent) { Chris@0: for (i = 0; i < toAdd.length; i++) { Chris@0: if (at != null) options.index = at + i; Chris@0: model = toAdd[i]; Chris@0: model.trigger('add', model, this, options); Chris@0: } Chris@0: if (sort || orderChanged) this.trigger('sort', this, options); Chris@0: if (toAdd.length || toRemove.length) this.trigger('update', this, options); Chris@0: } Chris@0: Chris@0: // Return the added (or merged) model (or models). Chris@0: return singular ? models[0] : models; Chris@0: }, Chris@0: Chris@0: // When you have more items than you want to add or remove individually, Chris@0: // you can reset the entire set with a new list of models, without firing Chris@0: // any granular `add` or `remove` events. Fires `reset` when finished. Chris@0: // Useful for bulk operations and optimizations. Chris@0: reset: function(models, options) { Chris@0: options = options ? _.clone(options) : {}; Chris@0: for (var i = 0; i < this.models.length; i++) { Chris@0: this._removeReference(this.models[i], options); Chris@0: } Chris@0: options.previousModels = this.models; Chris@0: this._reset(); Chris@0: models = this.add(models, _.extend({silent: true}, options)); Chris@0: if (!options.silent) this.trigger('reset', this, options); Chris@0: return models; Chris@0: }, Chris@0: Chris@0: // Add a model to the end of the collection. Chris@0: push: function(model, options) { Chris@0: return this.add(model, _.extend({at: this.length}, options)); Chris@0: }, Chris@0: Chris@0: // Remove a model from the end of the collection. Chris@0: pop: function(options) { Chris@0: var model = this.at(this.length - 1); Chris@0: return this.remove(model, options); Chris@0: }, Chris@0: Chris@0: // Add a model to the beginning of the collection. Chris@0: unshift: function(model, options) { Chris@0: return this.add(model, _.extend({at: 0}, options)); Chris@0: }, Chris@0: Chris@0: // Remove a model from the beginning of the collection. Chris@0: shift: function(options) { Chris@0: var model = this.at(0); Chris@0: return this.remove(model, options); Chris@0: }, Chris@0: Chris@0: // Slice out a sub-array of models from the collection. Chris@0: slice: function() { Chris@0: return slice.apply(this.models, arguments); Chris@0: }, Chris@0: Chris@0: // Get a model from the set by id. Chris@0: get: function(obj) { Chris@0: if (obj == null) return void 0; Chris@0: var id = this.modelId(this._isModel(obj) ? obj.attributes : obj); Chris@0: return this._byId[obj] || this._byId[id] || this._byId[obj.cid]; Chris@0: }, Chris@0: Chris@0: // Get the model at the given index. Chris@0: at: function(index) { Chris@0: if (index < 0) index += this.length; Chris@0: return this.models[index]; Chris@0: }, Chris@0: Chris@0: // Return models with matching attributes. Useful for simple cases of Chris@0: // `filter`. Chris@0: where: function(attrs, first) { Chris@0: return this[first ? 'find' : 'filter'](attrs); Chris@0: }, Chris@0: Chris@0: // Return the first model with matching attributes. Useful for simple cases Chris@0: // of `find`. Chris@0: findWhere: function(attrs) { Chris@0: return this.where(attrs, true); Chris@0: }, Chris@0: Chris@0: // Force the collection to re-sort itself. You don't need to call this under Chris@0: // normal circumstances, as the set will maintain sort order as each item Chris@0: // is added. Chris@0: sort: function(options) { Chris@0: var comparator = this.comparator; Chris@0: if (!comparator) throw new Error('Cannot sort a set without a comparator'); Chris@0: options || (options = {}); Chris@0: Chris@0: var length = comparator.length; Chris@0: if (_.isFunction(comparator)) comparator = _.bind(comparator, this); Chris@0: Chris@0: // Run sort based on type of `comparator`. Chris@0: if (length === 1 || _.isString(comparator)) { Chris@0: this.models = this.sortBy(comparator); Chris@0: } else { Chris@0: this.models.sort(comparator); Chris@0: } Chris@0: if (!options.silent) this.trigger('sort', this, options); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Pluck an attribute from each model in the collection. Chris@0: pluck: function(attr) { Chris@0: return _.invoke(this.models, 'get', attr); Chris@0: }, Chris@0: Chris@0: // Fetch the default set of models for this collection, resetting the Chris@0: // collection when they arrive. If `reset: true` is passed, the response Chris@0: // data will be passed through the `reset` method instead of `set`. Chris@0: fetch: function(options) { Chris@0: options = _.extend({parse: true}, options); Chris@0: var success = options.success; Chris@0: var collection = this; Chris@0: options.success = function(resp) { Chris@0: var method = options.reset ? 'reset' : 'set'; Chris@0: collection[method](resp, options); Chris@0: if (success) success.call(options.context, collection, resp, options); Chris@0: collection.trigger('sync', collection, resp, options); Chris@0: }; Chris@0: wrapError(this, options); Chris@0: return this.sync('read', this, options); Chris@0: }, Chris@0: Chris@0: // Create a new instance of a model in this collection. Add the model to the Chris@0: // collection immediately, unless `wait: true` is passed, in which case we Chris@0: // wait for the server to agree. Chris@0: create: function(model, options) { Chris@0: options = options ? _.clone(options) : {}; Chris@0: var wait = options.wait; Chris@0: model = this._prepareModel(model, options); Chris@0: if (!model) return false; Chris@0: if (!wait) this.add(model, options); Chris@0: var collection = this; Chris@0: var success = options.success; Chris@0: options.success = function(model, resp, callbackOpts) { Chris@0: if (wait) collection.add(model, callbackOpts); Chris@0: if (success) success.call(callbackOpts.context, model, resp, callbackOpts); Chris@0: }; Chris@0: model.save(null, options); Chris@0: return model; Chris@0: }, Chris@0: Chris@0: // **parse** converts a response into a list of models to be added to the Chris@0: // collection. The default implementation is just to pass it through. Chris@0: parse: function(resp, options) { Chris@0: return resp; Chris@0: }, Chris@0: Chris@0: // Create a new collection with an identical list of models as this one. Chris@0: clone: function() { Chris@0: return new this.constructor(this.models, { Chris@0: model: this.model, Chris@0: comparator: this.comparator Chris@0: }); Chris@0: }, Chris@0: Chris@0: // Define how to uniquely identify models in the collection. Chris@0: modelId: function (attrs) { Chris@0: return attrs[this.model.prototype.idAttribute || 'id']; Chris@0: }, Chris@0: Chris@0: // Private method to reset all internal state. Called when the collection Chris@0: // is first initialized or reset. Chris@0: _reset: function() { Chris@0: this.length = 0; Chris@0: this.models = []; Chris@0: this._byId = {}; Chris@0: }, Chris@0: Chris@0: // Prepare a hash of attributes (or other model) to be added to this Chris@0: // collection. Chris@0: _prepareModel: function(attrs, options) { Chris@0: if (this._isModel(attrs)) { Chris@0: if (!attrs.collection) attrs.collection = this; Chris@0: return attrs; Chris@0: } Chris@0: options = options ? _.clone(options) : {}; Chris@0: options.collection = this; Chris@0: var model = new this.model(attrs, options); Chris@0: if (!model.validationError) return model; Chris@0: this.trigger('invalid', this, model.validationError, options); Chris@0: return false; Chris@0: }, Chris@0: Chris@0: // Internal method called by both remove and set. Chris@0: _removeModels: function(models, options) { Chris@0: var removed = []; Chris@0: for (var i = 0; i < models.length; i++) { Chris@0: var model = this.get(models[i]); Chris@0: if (!model) continue; Chris@0: Chris@0: var index = this.indexOf(model); Chris@0: this.models.splice(index, 1); Chris@0: this.length--; Chris@0: Chris@0: if (!options.silent) { Chris@0: options.index = index; Chris@0: model.trigger('remove', model, this, options); Chris@0: } Chris@0: Chris@0: removed.push(model); Chris@0: this._removeReference(model, options); Chris@0: } Chris@0: return removed.length ? removed : false; Chris@0: }, Chris@0: Chris@0: // Method for checking whether an object should be considered a model for Chris@0: // the purposes of adding to the collection. Chris@0: _isModel: function (model) { Chris@0: return model instanceof Model; Chris@0: }, Chris@0: Chris@0: // Internal method to create a model's ties to a collection. Chris@0: _addReference: function(model, options) { Chris@0: this._byId[model.cid] = model; Chris@0: var id = this.modelId(model.attributes); Chris@0: if (id != null) this._byId[id] = model; Chris@0: model.on('all', this._onModelEvent, this); Chris@0: }, Chris@0: Chris@0: // Internal method to sever a model's ties to a collection. Chris@0: _removeReference: function(model, options) { Chris@0: delete this._byId[model.cid]; Chris@0: var id = this.modelId(model.attributes); Chris@0: if (id != null) delete this._byId[id]; Chris@0: if (this === model.collection) delete model.collection; Chris@0: model.off('all', this._onModelEvent, this); Chris@0: }, Chris@0: Chris@0: // Internal method called every time a model in the set fires an event. Chris@0: // Sets need to update their indexes when models change ids. All other Chris@0: // events simply proxy through. "add" and "remove" events that originate Chris@0: // in other collections are ignored. Chris@0: _onModelEvent: function(event, model, collection, options) { Chris@0: if ((event === 'add' || event === 'remove') && collection !== this) return; Chris@0: if (event === 'destroy') this.remove(model, options); Chris@0: if (event === 'change') { Chris@0: var prevId = this.modelId(model.previousAttributes()); Chris@0: var id = this.modelId(model.attributes); Chris@0: if (prevId !== id) { Chris@0: if (prevId != null) delete this._byId[prevId]; Chris@0: if (id != null) this._byId[id] = model; Chris@0: } Chris@0: } Chris@0: this.trigger.apply(this, arguments); Chris@0: } Chris@0: Chris@0: }); Chris@0: Chris@0: // Underscore methods that we want to implement on the Collection. Chris@0: // 90% of the core usefulness of Backbone Collections is actually implemented Chris@0: // right here: Chris@0: var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4, Chris@0: foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3, Chris@0: select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3, Chris@0: contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3, Chris@0: head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3, Chris@0: without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3, Chris@0: isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3, Chris@0: sortBy: 3, indexBy: 3}; Chris@0: Chris@0: // Mix in each Underscore method as a proxy to `Collection#models`. Chris@0: addUnderscoreMethods(Collection, collectionMethods, 'models'); Chris@0: Chris@0: // Backbone.View Chris@0: // ------------- Chris@0: Chris@0: // Backbone Views are almost more convention than they are actual code. A View Chris@0: // is simply a JavaScript object that represents a logical chunk of UI in the Chris@0: // DOM. This might be a single item, an entire list, a sidebar or panel, or Chris@0: // even the surrounding frame which wraps your whole app. Defining a chunk of Chris@0: // UI as a **View** allows you to define your DOM events declaratively, without Chris@0: // having to worry about render order ... and makes it easy for the view to Chris@0: // react to specific changes in the state of your models. Chris@0: Chris@0: // Creating a Backbone.View creates its initial element outside of the DOM, Chris@0: // if an existing element is not provided... Chris@0: var View = Backbone.View = function(options) { Chris@0: this.cid = _.uniqueId('view'); Chris@0: _.extend(this, _.pick(options, viewOptions)); Chris@0: this._ensureElement(); Chris@0: this.initialize.apply(this, arguments); Chris@0: }; Chris@0: Chris@0: // Cached regex to split keys for `delegate`. Chris@0: var delegateEventSplitter = /^(\S+)\s*(.*)$/; Chris@0: Chris@0: // List of view options to be set as properties. Chris@0: var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; Chris@0: Chris@0: // Set up all inheritable **Backbone.View** properties and methods. Chris@0: _.extend(View.prototype, Events, { Chris@0: Chris@0: // The default `tagName` of a View's element is `"div"`. Chris@0: tagName: 'div', Chris@0: Chris@0: // jQuery delegate for element lookup, scoped to DOM elements within the Chris@0: // current view. This should be preferred to global lookups where possible. Chris@0: $: function(selector) { Chris@0: return this.$el.find(selector); Chris@0: }, Chris@0: Chris@0: // Initialize is an empty function by default. Override it with your own Chris@0: // initialization logic. Chris@0: initialize: function(){}, Chris@0: Chris@0: // **render** is the core function that your view should override, in order Chris@0: // to populate its element (`this.el`), with the appropriate HTML. The Chris@0: // convention is for **render** to always return `this`. Chris@0: render: function() { Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Remove this view by taking the element out of the DOM, and removing any Chris@0: // applicable Backbone.Events listeners. Chris@0: remove: function() { Chris@0: this._removeElement(); Chris@0: this.stopListening(); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Remove this view's element from the document and all event listeners Chris@0: // attached to it. Exposed for subclasses using an alternative DOM Chris@0: // manipulation API. Chris@0: _removeElement: function() { Chris@0: this.$el.remove(); Chris@0: }, Chris@0: Chris@0: // Change the view's element (`this.el` property) and re-delegate the Chris@0: // view's events on the new element. Chris@0: setElement: function(element) { Chris@0: this.undelegateEvents(); Chris@0: this._setElement(element); Chris@0: this.delegateEvents(); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Creates the `this.el` and `this.$el` references for this view using the Chris@0: // given `el`. `el` can be a CSS selector or an HTML string, a jQuery Chris@0: // context or an element. Subclasses can override this to utilize an Chris@0: // alternative DOM manipulation API and are only required to set the Chris@0: // `this.el` property. Chris@0: _setElement: function(el) { Chris@0: this.$el = el instanceof Backbone.$ ? el : Backbone.$(el); Chris@0: this.el = this.$el[0]; Chris@0: }, Chris@0: Chris@0: // Set callbacks, where `this.events` is a hash of Chris@0: // Chris@0: // *{"event selector": "callback"}* Chris@0: // Chris@0: // { Chris@0: // 'mousedown .title': 'edit', Chris@0: // 'click .button': 'save', Chris@0: // 'click .open': function(e) { ... } Chris@0: // } Chris@0: // Chris@0: // pairs. Callbacks will be bound to the view, with `this` set properly. Chris@0: // Uses event delegation for efficiency. Chris@0: // Omitting the selector binds the event to `this.el`. Chris@0: delegateEvents: function(events) { Chris@0: events || (events = _.result(this, 'events')); Chris@0: if (!events) return this; Chris@0: this.undelegateEvents(); Chris@0: for (var key in events) { Chris@0: var method = events[key]; Chris@0: if (!_.isFunction(method)) method = this[method]; Chris@0: if (!method) continue; Chris@0: var match = key.match(delegateEventSplitter); Chris@0: this.delegate(match[1], match[2], _.bind(method, this)); Chris@0: } Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Add a single event listener to the view's element (or a child element Chris@0: // using `selector`). This only works for delegate-able events: not `focus`, Chris@0: // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer. Chris@0: delegate: function(eventName, selector, listener) { Chris@0: this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Clears all callbacks previously bound to the view by `delegateEvents`. Chris@0: // You usually don't need to use this, but may wish to if you have multiple Chris@0: // Backbone views attached to the same DOM element. Chris@0: undelegateEvents: function() { Chris@0: if (this.$el) this.$el.off('.delegateEvents' + this.cid); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // A finer-grained `undelegateEvents` for removing a single delegated event. Chris@0: // `selector` and `listener` are both optional. Chris@0: undelegate: function(eventName, selector, listener) { Chris@0: this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Produces a DOM element to be assigned to your view. Exposed for Chris@0: // subclasses using an alternative DOM manipulation API. Chris@0: _createElement: function(tagName) { Chris@0: return document.createElement(tagName); Chris@0: }, Chris@0: Chris@0: // Ensure that the View has a DOM element to render into. Chris@0: // If `this.el` is a string, pass it through `$()`, take the first Chris@0: // matching element, and re-assign it to `el`. Otherwise, create Chris@0: // an element from the `id`, `className` and `tagName` properties. Chris@0: _ensureElement: function() { Chris@0: if (!this.el) { Chris@0: var attrs = _.extend({}, _.result(this, 'attributes')); Chris@0: if (this.id) attrs.id = _.result(this, 'id'); Chris@0: if (this.className) attrs['class'] = _.result(this, 'className'); Chris@0: this.setElement(this._createElement(_.result(this, 'tagName'))); Chris@0: this._setAttributes(attrs); Chris@0: } else { Chris@0: this.setElement(_.result(this, 'el')); Chris@0: } Chris@0: }, Chris@0: Chris@0: // Set attributes from a hash on this view's element. Exposed for Chris@0: // subclasses using an alternative DOM manipulation API. Chris@0: _setAttributes: function(attributes) { Chris@0: this.$el.attr(attributes); Chris@0: } Chris@0: Chris@0: }); Chris@0: Chris@0: // Backbone.sync Chris@0: // ------------- Chris@0: Chris@0: // Override this function to change the manner in which Backbone persists Chris@0: // models to the server. You will be passed the type of request, and the Chris@0: // model in question. By default, makes a RESTful Ajax request Chris@0: // to the model's `url()`. Some possible customizations could be: Chris@0: // Chris@0: // * Use `setTimeout` to batch rapid-fire updates into a single request. Chris@0: // * Send up the models as XML instead of JSON. Chris@0: // * Persist models via WebSockets instead of Ajax. Chris@0: // Chris@0: // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests Chris@0: // as `POST`, with a `_method` parameter containing the true HTTP method, Chris@0: // as well as all requests with the body as `application/x-www-form-urlencoded` Chris@0: // instead of `application/json` with the model in a param named `model`. Chris@0: // Useful when interfacing with server-side languages like **PHP** that make Chris@0: // it difficult to read the body of `PUT` requests. Chris@0: Backbone.sync = function(method, model, options) { Chris@0: var type = methodMap[method]; Chris@0: Chris@0: // Default options, unless specified. Chris@0: _.defaults(options || (options = {}), { Chris@0: emulateHTTP: Backbone.emulateHTTP, Chris@0: emulateJSON: Backbone.emulateJSON Chris@0: }); Chris@0: Chris@0: // Default JSON-request options. Chris@0: var params = {type: type, dataType: 'json'}; Chris@0: Chris@0: // Ensure that we have a URL. Chris@0: if (!options.url) { Chris@0: params.url = _.result(model, 'url') || urlError(); Chris@0: } Chris@0: Chris@0: // Ensure that we have the appropriate request data. Chris@0: if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { Chris@0: params.contentType = 'application/json'; Chris@0: params.data = JSON.stringify(options.attrs || model.toJSON(options)); Chris@0: } Chris@0: Chris@0: // For older servers, emulate JSON by encoding the request into an HTML-form. Chris@0: if (options.emulateJSON) { Chris@0: params.contentType = 'application/x-www-form-urlencoded'; Chris@0: params.data = params.data ? {model: params.data} : {}; Chris@0: } Chris@0: Chris@0: // For older servers, emulate HTTP by mimicking the HTTP method with `_method` Chris@0: // And an `X-HTTP-Method-Override` header. Chris@0: if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { Chris@0: params.type = 'POST'; Chris@0: if (options.emulateJSON) params.data._method = type; Chris@0: var beforeSend = options.beforeSend; Chris@0: options.beforeSend = function(xhr) { Chris@0: xhr.setRequestHeader('X-HTTP-Method-Override', type); Chris@0: if (beforeSend) return beforeSend.apply(this, arguments); Chris@0: }; Chris@0: } Chris@0: Chris@0: // Don't process data on a non-GET request. Chris@0: if (params.type !== 'GET' && !options.emulateJSON) { Chris@0: params.processData = false; Chris@0: } Chris@0: Chris@0: // Pass along `textStatus` and `errorThrown` from jQuery. Chris@0: var error = options.error; Chris@0: options.error = function(xhr, textStatus, errorThrown) { Chris@0: options.textStatus = textStatus; Chris@0: options.errorThrown = errorThrown; Chris@0: if (error) error.call(options.context, xhr, textStatus, errorThrown); Chris@0: }; Chris@0: Chris@0: // Make the request, allowing the user to override any Ajax options. Chris@0: var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); Chris@0: model.trigger('request', model, xhr, options); Chris@0: return xhr; Chris@0: }; Chris@0: Chris@0: // Map from CRUD to HTTP for our default `Backbone.sync` implementation. Chris@0: var methodMap = { Chris@0: 'create': 'POST', Chris@0: 'update': 'PUT', Chris@0: 'patch': 'PATCH', Chris@0: 'delete': 'DELETE', Chris@0: 'read': 'GET' Chris@0: }; Chris@0: Chris@0: // Set the default implementation of `Backbone.ajax` to proxy through to `$`. Chris@0: // Override this if you'd like to use a different library. Chris@0: Backbone.ajax = function() { Chris@0: return Backbone.$.ajax.apply(Backbone.$, arguments); Chris@0: }; Chris@0: Chris@0: // Backbone.Router Chris@0: // --------------- Chris@0: Chris@0: // Routers map faux-URLs to actions, and fire events when routes are Chris@0: // matched. Creating a new one sets its `routes` hash, if not set statically. Chris@0: var Router = Backbone.Router = function(options) { Chris@0: options || (options = {}); Chris@0: if (options.routes) this.routes = options.routes; Chris@0: this._bindRoutes(); Chris@0: this.initialize.apply(this, arguments); Chris@0: }; Chris@0: Chris@0: // Cached regular expressions for matching named param parts and splatted Chris@0: // parts of route strings. Chris@0: var optionalParam = /\((.*?)\)/g; Chris@0: var namedParam = /(\(\?)?:\w+/g; Chris@0: var splatParam = /\*\w+/g; Chris@0: var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; Chris@0: Chris@0: // Set up all inheritable **Backbone.Router** properties and methods. Chris@0: _.extend(Router.prototype, Events, { Chris@0: Chris@0: // Initialize is an empty function by default. Override it with your own Chris@0: // initialization logic. Chris@0: initialize: function(){}, Chris@0: Chris@0: // Manually bind a single named route to a callback. For example: Chris@0: // Chris@0: // this.route('search/:query/p:num', 'search', function(query, num) { Chris@0: // ... Chris@0: // }); Chris@0: // Chris@0: route: function(route, name, callback) { Chris@0: if (!_.isRegExp(route)) route = this._routeToRegExp(route); Chris@0: if (_.isFunction(name)) { Chris@0: callback = name; Chris@0: name = ''; Chris@0: } Chris@0: if (!callback) callback = this[name]; Chris@0: var router = this; Chris@0: Backbone.history.route(route, function(fragment) { Chris@0: var args = router._extractParameters(route, fragment); Chris@0: if (router.execute(callback, args, name) !== false) { Chris@0: router.trigger.apply(router, ['route:' + name].concat(args)); Chris@0: router.trigger('route', name, args); Chris@0: Backbone.history.trigger('route', router, name, args); Chris@0: } Chris@0: }); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Execute a route handler with the provided parameters. This is an Chris@0: // excellent place to do pre-route setup or post-route cleanup. Chris@0: execute: function(callback, args, name) { Chris@0: if (callback) callback.apply(this, args); Chris@0: }, Chris@0: Chris@0: // Simple proxy to `Backbone.history` to save a fragment into the history. Chris@0: navigate: function(fragment, options) { Chris@0: Backbone.history.navigate(fragment, options); Chris@0: return this; Chris@0: }, Chris@0: Chris@0: // Bind all defined routes to `Backbone.history`. We have to reverse the Chris@0: // order of the routes here to support behavior where the most general Chris@0: // routes can be defined at the bottom of the route map. Chris@0: _bindRoutes: function() { Chris@0: if (!this.routes) return; Chris@0: this.routes = _.result(this, 'routes'); Chris@0: var route, routes = _.keys(this.routes); Chris@0: while ((route = routes.pop()) != null) { Chris@0: this.route(route, this.routes[route]); Chris@0: } Chris@0: }, Chris@0: Chris@0: // Convert a route string into a regular expression, suitable for matching Chris@0: // against the current location hash. Chris@0: _routeToRegExp: function(route) { Chris@0: route = route.replace(escapeRegExp, '\\$&') Chris@0: .replace(optionalParam, '(?:$1)?') Chris@0: .replace(namedParam, function(match, optional) { Chris@0: return optional ? match : '([^/?]+)'; Chris@0: }) Chris@0: .replace(splatParam, '([^?]*?)'); Chris@0: return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); Chris@0: }, Chris@0: Chris@0: // Given a route, and a URL fragment that it matches, return the array of Chris@0: // extracted decoded parameters. Empty or unmatched parameters will be Chris@0: // treated as `null` to normalize cross-browser behavior. Chris@0: _extractParameters: function(route, fragment) { Chris@0: var params = route.exec(fragment).slice(1); Chris@0: return _.map(params, function(param, i) { Chris@0: // Don't decode the search params. Chris@0: if (i === params.length - 1) return param || null; Chris@0: return param ? decodeURIComponent(param) : null; Chris@0: }); Chris@0: } Chris@0: Chris@0: }); Chris@0: Chris@0: // Backbone.History Chris@0: // ---------------- Chris@0: Chris@0: // Handles cross-browser history management, based on either Chris@0: // [pushState](http://diveintohtml5.info/history.html) and real URLs, or Chris@0: // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) Chris@0: // and URL fragments. If the browser supports neither (old IE, natch), Chris@0: // falls back to polling. Chris@0: var History = Backbone.History = function() { Chris@0: this.handlers = []; Chris@0: this.checkUrl = _.bind(this.checkUrl, this); Chris@0: Chris@0: // Ensure that `History` can be used outside of the browser. Chris@0: if (typeof window !== 'undefined') { Chris@0: this.location = window.location; Chris@0: this.history = window.history; Chris@0: } Chris@0: }; Chris@0: Chris@0: // Cached regex for stripping a leading hash/slash and trailing space. Chris@0: var routeStripper = /^[#\/]|\s+$/g; Chris@0: Chris@0: // Cached regex for stripping leading and trailing slashes. Chris@0: var rootStripper = /^\/+|\/+$/g; Chris@0: Chris@0: // Cached regex for stripping urls of hash. Chris@0: var pathStripper = /#.*$/; Chris@0: Chris@0: // Has the history handling already been started? Chris@0: History.started = false; Chris@0: Chris@0: // Set up all inheritable **Backbone.History** properties and methods. Chris@0: _.extend(History.prototype, Events, { Chris@0: Chris@0: // The default interval to poll for hash changes, if necessary, is Chris@0: // twenty times a second. Chris@0: interval: 50, Chris@0: Chris@0: // Are we at the app root? Chris@0: atRoot: function() { Chris@0: var path = this.location.pathname.replace(/[^\/]$/, '$&/'); Chris@0: return path === this.root && !this.getSearch(); Chris@0: }, Chris@0: Chris@0: // Does the pathname match the root? Chris@0: matchRoot: function() { Chris@0: var path = this.decodeFragment(this.location.pathname); Chris@0: var root = path.slice(0, this.root.length - 1) + '/'; Chris@0: return root === this.root; Chris@0: }, Chris@0: Chris@0: // Unicode characters in `location.pathname` are percent encoded so they're Chris@0: // decoded for comparison. `%25` should not be decoded since it may be part Chris@0: // of an encoded parameter. Chris@0: decodeFragment: function(fragment) { Chris@0: return decodeURI(fragment.replace(/%25/g, '%2525')); Chris@0: }, Chris@0: Chris@0: // In IE6, the hash fragment and search params are incorrect if the Chris@0: // fragment contains `?`. Chris@0: getSearch: function() { Chris@0: var match = this.location.href.replace(/#.*/, '').match(/\?.+/); Chris@0: return match ? match[0] : ''; Chris@0: }, Chris@0: Chris@0: // Gets the true hash value. Cannot use location.hash directly due to bug Chris@0: // in Firefox where location.hash will always be decoded. Chris@0: getHash: function(window) { Chris@0: var match = (window || this).location.href.match(/#(.*)$/); Chris@0: return match ? match[1] : ''; Chris@0: }, Chris@0: Chris@0: // Get the pathname and search params, without the root. Chris@0: getPath: function() { Chris@0: var path = this.decodeFragment( Chris@0: this.location.pathname + this.getSearch() Chris@0: ).slice(this.root.length - 1); Chris@0: return path.charAt(0) === '/' ? path.slice(1) : path; Chris@0: }, Chris@0: Chris@0: // Get the cross-browser normalized URL fragment from the path or hash. Chris@0: getFragment: function(fragment) { Chris@0: if (fragment == null) { Chris@0: if (this._usePushState || !this._wantsHashChange) { Chris@0: fragment = this.getPath(); Chris@0: } else { Chris@0: fragment = this.getHash(); Chris@0: } Chris@0: } Chris@0: return fragment.replace(routeStripper, ''); Chris@0: }, Chris@0: Chris@0: // Start the hash change handling, returning `true` if the current URL matches Chris@0: // an existing route, and `false` otherwise. Chris@0: start: function(options) { Chris@0: if (History.started) throw new Error('Backbone.history has already been started'); Chris@0: History.started = true; Chris@0: Chris@0: // Figure out the initial configuration. Do we need an iframe? Chris@0: // Is pushState desired ... is it available? Chris@0: this.options = _.extend({root: '/'}, this.options, options); Chris@0: this.root = this.options.root; Chris@0: this._wantsHashChange = this.options.hashChange !== false; Chris@0: this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7); Chris@0: this._useHashChange = this._wantsHashChange && this._hasHashChange; Chris@0: this._wantsPushState = !!this.options.pushState; Chris@0: this._hasPushState = !!(this.history && this.history.pushState); Chris@0: this._usePushState = this._wantsPushState && this._hasPushState; Chris@0: this.fragment = this.getFragment(); Chris@0: Chris@0: // Normalize root to always include a leading and trailing slash. Chris@0: this.root = ('/' + this.root + '/').replace(rootStripper, '/'); Chris@0: Chris@0: // Transition from hashChange to pushState or vice versa if both are Chris@0: // requested. Chris@0: if (this._wantsHashChange && this._wantsPushState) { Chris@0: Chris@0: // If we've started off with a route from a `pushState`-enabled Chris@0: // browser, but we're currently in a browser that doesn't support it... Chris@0: if (!this._hasPushState && !this.atRoot()) { Chris@0: var root = this.root.slice(0, -1) || '/'; Chris@0: this.location.replace(root + '#' + this.getPath()); Chris@0: // Return immediately as browser will do redirect to new url Chris@0: return true; Chris@0: Chris@0: // Or if we've started out with a hash-based route, but we're currently Chris@0: // in a browser where it could be `pushState`-based instead... Chris@0: } else if (this._hasPushState && this.atRoot()) { Chris@0: this.navigate(this.getHash(), {replace: true}); Chris@0: } Chris@0: Chris@0: } Chris@0: Chris@0: // Proxy an iframe to handle location events if the browser doesn't Chris@0: // support the `hashchange` event, HTML5 history, or the user wants Chris@0: // `hashChange` but not `pushState`. Chris@0: if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) { Chris@0: this.iframe = document.createElement('iframe'); Chris@0: this.iframe.src = 'javascript:0'; Chris@0: this.iframe.style.display = 'none'; Chris@0: this.iframe.tabIndex = -1; Chris@0: var body = document.body; Chris@0: // Using `appendChild` will throw on IE < 9 if the document is not ready. Chris@0: var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow; Chris@0: iWindow.document.open(); Chris@0: iWindow.document.close(); Chris@0: iWindow.location.hash = '#' + this.fragment; Chris@0: } Chris@0: Chris@0: // Add a cross-platform `addEventListener` shim for older browsers. Chris@0: var addEventListener = window.addEventListener || function (eventName, listener) { Chris@0: return attachEvent('on' + eventName, listener); Chris@0: }; Chris@0: Chris@0: // Depending on whether we're using pushState or hashes, and whether Chris@0: // 'onhashchange' is supported, determine how we check the URL state. Chris@0: if (this._usePushState) { Chris@0: addEventListener('popstate', this.checkUrl, false); Chris@0: } else if (this._useHashChange && !this.iframe) { Chris@0: addEventListener('hashchange', this.checkUrl, false); Chris@0: } else if (this._wantsHashChange) { Chris@0: this._checkUrlInterval = setInterval(this.checkUrl, this.interval); Chris@0: } Chris@0: Chris@0: if (!this.options.silent) return this.loadUrl(); Chris@0: }, Chris@0: Chris@0: // Disable Backbone.history, perhaps temporarily. Not useful in a real app, Chris@0: // but possibly useful for unit testing Routers. Chris@0: stop: function() { Chris@0: // Add a cross-platform `removeEventListener` shim for older browsers. Chris@0: var removeEventListener = window.removeEventListener || function (eventName, listener) { Chris@0: return detachEvent('on' + eventName, listener); Chris@0: }; Chris@0: Chris@0: // Remove window listeners. Chris@0: if (this._usePushState) { Chris@0: removeEventListener('popstate', this.checkUrl, false); Chris@0: } else if (this._useHashChange && !this.iframe) { Chris@0: removeEventListener('hashchange', this.checkUrl, false); Chris@0: } Chris@0: Chris@0: // Clean up the iframe if necessary. Chris@0: if (this.iframe) { Chris@0: document.body.removeChild(this.iframe); Chris@0: this.iframe = null; Chris@0: } Chris@0: Chris@0: // Some environments will throw when clearing an undefined interval. Chris@0: if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); Chris@0: History.started = false; Chris@0: }, Chris@0: Chris@0: // Add a route to be tested when the fragment changes. Routes added later Chris@0: // may override previous routes. Chris@0: route: function(route, callback) { Chris@0: this.handlers.unshift({route: route, callback: callback}); Chris@0: }, Chris@0: Chris@0: // Checks the current URL to see if it has changed, and if it has, Chris@0: // calls `loadUrl`, normalizing across the hidden iframe. Chris@0: checkUrl: function(e) { Chris@0: var current = this.getFragment(); Chris@0: Chris@0: // If the user pressed the back button, the iframe's hash will have Chris@0: // changed and we should use that for comparison. Chris@0: if (current === this.fragment && this.iframe) { Chris@0: current = this.getHash(this.iframe.contentWindow); Chris@0: } Chris@0: Chris@0: if (current === this.fragment) return false; Chris@0: if (this.iframe) this.navigate(current); Chris@0: this.loadUrl(); Chris@0: }, Chris@0: Chris@0: // Attempt to load the current URL fragment. If a route succeeds with a Chris@0: // match, returns `true`. If no defined routes matches the fragment, Chris@0: // returns `false`. Chris@0: loadUrl: function(fragment) { Chris@0: // If the root doesn't match, no routes can match either. Chris@0: if (!this.matchRoot()) return false; Chris@0: fragment = this.fragment = this.getFragment(fragment); Chris@0: return _.some(this.handlers, function(handler) { Chris@0: if (handler.route.test(fragment)) { Chris@0: handler.callback(fragment); Chris@0: return true; Chris@0: } Chris@0: }); Chris@0: }, Chris@0: Chris@0: // Save a fragment into the hash history, or replace the URL state if the Chris@0: // 'replace' option is passed. You are responsible for properly URL-encoding Chris@0: // the fragment in advance. Chris@0: // Chris@0: // The options object can contain `trigger: true` if you wish to have the Chris@0: // route callback be fired (not usually desirable), or `replace: true`, if Chris@0: // you wish to modify the current URL without adding an entry to the history. Chris@0: navigate: function(fragment, options) { Chris@0: if (!History.started) return false; Chris@0: if (!options || options === true) options = {trigger: !!options}; Chris@0: Chris@0: // Normalize the fragment. Chris@0: fragment = this.getFragment(fragment || ''); Chris@0: Chris@0: // Don't include a trailing slash on the root. Chris@0: var root = this.root; Chris@0: if (fragment === '' || fragment.charAt(0) === '?') { Chris@0: root = root.slice(0, -1) || '/'; Chris@0: } Chris@0: var url = root + fragment; Chris@0: Chris@0: // Strip the hash and decode for matching. Chris@0: fragment = this.decodeFragment(fragment.replace(pathStripper, '')); Chris@0: Chris@0: if (this.fragment === fragment) return; Chris@0: this.fragment = fragment; Chris@0: Chris@0: // If pushState is available, we use it to set the fragment as a real URL. Chris@0: if (this._usePushState) { Chris@0: this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); Chris@0: Chris@0: // If hash changes haven't been explicitly disabled, update the hash Chris@0: // fragment to store history. Chris@0: } else if (this._wantsHashChange) { Chris@0: this._updateHash(this.location, fragment, options.replace); Chris@0: if (this.iframe && (fragment !== this.getHash(this.iframe.contentWindow))) { Chris@0: var iWindow = this.iframe.contentWindow; Chris@0: Chris@0: // Opening and closing the iframe tricks IE7 and earlier to push a Chris@0: // history entry on hash-tag change. When replace is true, we don't Chris@0: // want this. Chris@0: if (!options.replace) { Chris@0: iWindow.document.open(); Chris@0: iWindow.document.close(); Chris@0: } Chris@0: Chris@0: this._updateHash(iWindow.location, fragment, options.replace); Chris@0: } Chris@0: Chris@0: // If you've told us that you explicitly don't want fallback hashchange- Chris@0: // based history, then `navigate` becomes a page refresh. Chris@0: } else { Chris@0: return this.location.assign(url); Chris@0: } Chris@0: if (options.trigger) return this.loadUrl(fragment); Chris@0: }, Chris@0: Chris@0: // Update the hash location, either replacing the current entry, or adding Chris@0: // a new one to the browser history. Chris@0: _updateHash: function(location, fragment, replace) { Chris@0: if (replace) { Chris@0: var href = location.href.replace(/(javascript:|#).*$/, ''); Chris@0: location.replace(href + '#' + fragment); Chris@0: } else { Chris@0: // Some browsers require that `hash` contains a leading #. Chris@0: location.hash = '#' + fragment; Chris@0: } Chris@0: } Chris@0: Chris@0: }); Chris@0: Chris@0: // Create the default Backbone.history. Chris@0: Backbone.history = new History; Chris@0: Chris@0: // Helpers Chris@0: // ------- Chris@0: Chris@0: // Helper function to correctly set up the prototype chain for subclasses. Chris@0: // Similar to `goog.inherits`, but uses a hash of prototype properties and Chris@0: // class properties to be extended. Chris@0: var extend = function(protoProps, staticProps) { Chris@0: var parent = this; Chris@0: var child; Chris@0: Chris@0: // The constructor function for the new subclass is either defined by you Chris@0: // (the "constructor" property in your `extend` definition), or defaulted Chris@0: // by us to simply call the parent constructor. Chris@0: if (protoProps && _.has(protoProps, 'constructor')) { Chris@0: child = protoProps.constructor; Chris@0: } else { Chris@0: child = function(){ return parent.apply(this, arguments); }; Chris@0: } Chris@0: Chris@0: // Add static properties to the constructor function, if supplied. Chris@0: _.extend(child, parent, staticProps); Chris@0: Chris@0: // Set the prototype chain to inherit from `parent`, without calling Chris@0: // `parent` constructor function. Chris@0: var Surrogate = function(){ this.constructor = child; }; Chris@0: Surrogate.prototype = parent.prototype; Chris@0: child.prototype = new Surrogate; Chris@0: Chris@0: // Add prototype properties (instance properties) to the subclass, Chris@0: // if supplied. Chris@0: if (protoProps) _.extend(child.prototype, protoProps); Chris@0: Chris@0: // Set a convenience property in case the parent's prototype is needed Chris@0: // later. Chris@0: child.__super__ = parent.prototype; Chris@0: Chris@0: return child; Chris@0: }; Chris@0: Chris@0: // Set up inheritance for the model, collection, router, view and history. Chris@0: Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; Chris@0: Chris@0: // Throw an error when a URL is needed, and none is supplied. Chris@0: var urlError = function() { Chris@0: throw new Error('A "url" property or function must be specified'); Chris@0: }; Chris@0: Chris@0: // Wrap an optional error callback with a fallback error event. Chris@0: var wrapError = function(model, options) { Chris@0: var error = options.error; Chris@0: options.error = function(resp) { Chris@0: if (error) error.call(options.context, model, resp, options); Chris@0: model.trigger('error', model, resp, options); Chris@0: }; Chris@0: }; Chris@0: Chris@0: return Backbone; Chris@0: Chris@0: }));