Daniel@0: // Backbone.js 1.1.2 Daniel@0: Daniel@0: // (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors Daniel@0: // Backbone may be freely distributed under the MIT license. Daniel@0: // For all details and documentation: Daniel@0: // http://backbonejs.org Daniel@0: Daniel@0: (function(root, factory) { Daniel@0: Daniel@0: // Set up Backbone appropriately for the environment. Start with AMD. Daniel@0: if (typeof define === 'function' && define.amd) { Daniel@0: define(['underscore', 'jquery', 'exports'], function(_, $, exports) { Daniel@0: // Export global even in AMD case in case this script is loaded with Daniel@0: // others that may still expect a global Backbone. Daniel@0: root.Backbone = factory(root, exports, _, $); Daniel@0: }); Daniel@0: Daniel@0: // Next for Node.js or CommonJS. jQuery may not be needed as a module. Daniel@0: } else if (typeof exports !== 'undefined') { Daniel@0: var _ = require('underscore'); Daniel@0: factory(root, exports, _); Daniel@0: Daniel@0: // Finally, as a browser global. Daniel@0: } else { Daniel@0: root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); Daniel@0: } Daniel@0: Daniel@0: }(this, function(root, Backbone, _, $) { Daniel@0: Daniel@0: // Initial Setup Daniel@0: // ------------- Daniel@0: Daniel@0: // Save the previous value of the `Backbone` variable, so that it can be Daniel@0: // restored later on, if `noConflict` is used. Daniel@0: var previousBackbone = root.Backbone; Daniel@0: Daniel@0: // Create local references to array methods we'll want to use later. Daniel@0: var array = []; Daniel@0: var push = array.push; Daniel@0: var slice = array.slice; Daniel@0: var splice = array.splice; Daniel@0: Daniel@0: // Current version of the library. Keep in sync with `package.json`. Daniel@0: Backbone.VERSION = '1.1.2'; Daniel@0: Daniel@0: // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns Daniel@0: // the `$` variable. Daniel@0: Backbone.$ = $; Daniel@0: Daniel@0: // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable Daniel@0: // to its previous owner. Returns a reference to this Backbone object. Daniel@0: Backbone.noConflict = function() { Daniel@0: root.Backbone = previousBackbone; Daniel@0: return this; Daniel@0: }; Daniel@0: Daniel@0: // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option Daniel@0: // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and Daniel@0: // set a `X-Http-Method-Override` header. Daniel@0: Backbone.emulateHTTP = false; Daniel@0: Daniel@0: // Turn on `emulateJSON` to support legacy servers that can't deal with direct Daniel@0: // `application/json` requests ... will encode the body as Daniel@0: // `application/x-www-form-urlencoded` instead and will send the model in a Daniel@0: // form param named `model`. Daniel@0: Backbone.emulateJSON = false; Daniel@0: Daniel@0: // Backbone.Events Daniel@0: // --------------- Daniel@0: Daniel@0: // A module that can be mixed in to *any object* in order to provide it with Daniel@0: // custom events. You may bind with `on` or remove with `off` callback Daniel@0: // functions to an event; `trigger`-ing an event fires all callbacks in Daniel@0: // succession. Daniel@0: // Daniel@0: // var object = {}; Daniel@0: // _.extend(object, Backbone.Events); Daniel@0: // object.on('expand', function(){ alert('expanded'); }); Daniel@0: // object.trigger('expand'); Daniel@0: // Daniel@0: var Events = Backbone.Events = { Daniel@0: Daniel@0: // Bind an event to a `callback` function. Passing `"all"` will bind Daniel@0: // the callback to all events fired. Daniel@0: on: function(name, callback, context) { Daniel@0: if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; Daniel@0: this._events || (this._events = {}); Daniel@0: var events = this._events[name] || (this._events[name] = []); Daniel@0: events.push({callback: callback, context: context, ctx: context || this}); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Bind an event to only be triggered a single time. After the first time Daniel@0: // the callback is invoked, it will be removed. Daniel@0: once: function(name, callback, context) { Daniel@0: if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; Daniel@0: var self = this; Daniel@0: var once = _.once(function() { Daniel@0: self.off(name, once); Daniel@0: callback.apply(this, arguments); Daniel@0: }); Daniel@0: once._callback = callback; Daniel@0: return this.on(name, once, context); Daniel@0: }, Daniel@0: Daniel@0: // Remove one or many callbacks. If `context` is null, removes all Daniel@0: // callbacks with that function. If `callback` is null, removes all Daniel@0: // callbacks for the event. If `name` is null, removes all bound Daniel@0: // callbacks for all events. Daniel@0: off: function(name, callback, context) { Daniel@0: var retain, ev, events, names, i, l, j, k; Daniel@0: if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; Daniel@0: if (!name && !callback && !context) { Daniel@0: this._events = void 0; Daniel@0: return this; Daniel@0: } Daniel@0: names = name ? [name] : _.keys(this._events); Daniel@0: for (i = 0, l = names.length; i < l; i++) { Daniel@0: name = names[i]; Daniel@0: if (events = this._events[name]) { Daniel@0: this._events[name] = retain = []; Daniel@0: if (callback || context) { Daniel@0: for (j = 0, k = events.length; j < k; j++) { Daniel@0: ev = events[j]; Daniel@0: if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || Daniel@0: (context && context !== ev.context)) { Daniel@0: retain.push(ev); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: if (!retain.length) delete this._events[name]; Daniel@0: } Daniel@0: } Daniel@0: Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Trigger one or many events, firing all bound callbacks. Callbacks are Daniel@0: // passed the same arguments as `trigger` is, apart from the event name Daniel@0: // (unless you're listening on `"all"`, which will cause your callback to Daniel@0: // receive the true name of the event as the first argument). Daniel@0: trigger: function(name) { Daniel@0: if (!this._events) return this; Daniel@0: var args = slice.call(arguments, 1); Daniel@0: if (!eventsApi(this, 'trigger', name, args)) return this; Daniel@0: var events = this._events[name]; Daniel@0: var allEvents = this._events.all; Daniel@0: if (events) triggerEvents(events, args); Daniel@0: if (allEvents) triggerEvents(allEvents, arguments); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Tell this object to stop listening to either specific events ... or Daniel@0: // to every object it's currently listening to. Daniel@0: stopListening: function(obj, name, callback) { Daniel@0: var listeningTo = this._listeningTo; Daniel@0: if (!listeningTo) return this; Daniel@0: var remove = !name && !callback; Daniel@0: if (!callback && typeof name === 'object') callback = this; Daniel@0: if (obj) (listeningTo = {})[obj._listenId] = obj; Daniel@0: for (var id in listeningTo) { Daniel@0: obj = listeningTo[id]; Daniel@0: obj.off(name, callback, this); Daniel@0: if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; Daniel@0: } Daniel@0: return this; Daniel@0: } Daniel@0: Daniel@0: }; Daniel@0: Daniel@0: // Regular expression used to split event strings. Daniel@0: var eventSplitter = /\s+/; Daniel@0: Daniel@0: // Implement fancy features of the Events API such as multiple event Daniel@0: // names `"change blur"` and jQuery-style event maps `{change: action}` Daniel@0: // in terms of the existing API. Daniel@0: var eventsApi = function(obj, action, name, rest) { Daniel@0: if (!name) return true; Daniel@0: Daniel@0: // Handle event maps. Daniel@0: if (typeof name === 'object') { Daniel@0: for (var key in name) { Daniel@0: obj[action].apply(obj, [key, name[key]].concat(rest)); Daniel@0: } Daniel@0: return false; Daniel@0: } Daniel@0: Daniel@0: // Handle space separated event names. Daniel@0: if (eventSplitter.test(name)) { Daniel@0: var names = name.split(eventSplitter); Daniel@0: for (var i = 0, l = names.length; i < l; i++) { Daniel@0: obj[action].apply(obj, [names[i]].concat(rest)); Daniel@0: } Daniel@0: return false; Daniel@0: } Daniel@0: Daniel@0: return true; Daniel@0: }; Daniel@0: Daniel@0: // A difficult-to-believe, but optimized internal dispatch function for Daniel@0: // triggering events. Tries to keep the usual cases speedy (most internal Daniel@0: // Backbone events have 3 arguments). Daniel@0: var triggerEvents = function(events, args) { Daniel@0: var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; Daniel@0: switch (args.length) { Daniel@0: case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; Daniel@0: case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; Daniel@0: case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; Daniel@0: case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; Daniel@0: default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; Daniel@0: } Daniel@0: }; Daniel@0: Daniel@0: var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; Daniel@0: Daniel@0: // Inversion-of-control versions of `on` and `once`. Tell *this* object to Daniel@0: // listen to an event in another object ... keeping track of what it's Daniel@0: // listening to. Daniel@0: _.each(listenMethods, function(implementation, method) { Daniel@0: Events[method] = function(obj, name, callback) { Daniel@0: var listeningTo = this._listeningTo || (this._listeningTo = {}); Daniel@0: var id = obj._listenId || (obj._listenId = _.uniqueId('l')); Daniel@0: listeningTo[id] = obj; Daniel@0: if (!callback && typeof name === 'object') callback = this; Daniel@0: obj[implementation](name, callback, this); Daniel@0: return this; Daniel@0: }; Daniel@0: }); Daniel@0: Daniel@0: // Aliases for backwards compatibility. Daniel@0: Events.bind = Events.on; Daniel@0: Events.unbind = Events.off; Daniel@0: Daniel@0: // Allow the `Backbone` object to serve as a global event bus, for folks who Daniel@0: // want global "pubsub" in a convenient place. Daniel@0: _.extend(Backbone, Events); Daniel@0: Daniel@0: // Backbone.Model Daniel@0: // -------------- Daniel@0: Daniel@0: // Backbone **Models** are the basic data object in the framework -- Daniel@0: // frequently representing a row in a table in a database on your server. Daniel@0: // A discrete chunk of data and a bunch of useful, related methods for Daniel@0: // performing computations and transformations on that data. Daniel@0: Daniel@0: // Create a new model with the specified attributes. A client id (`cid`) Daniel@0: // is automatically generated and assigned for you. Daniel@0: var Model = Backbone.Model = function(attributes, options) { Daniel@0: var attrs = attributes || {}; Daniel@0: options || (options = {}); Daniel@0: //MODIFIED Daniel@0: //this.cid = _.uniqueId('c'); Daniel@0: this.cid = _.uniqueId(this.cidPrefix || 'c'); Daniel@0: this.attributes = {}; Daniel@0: if (options.collection) this.collection = options.collection; Daniel@0: if (options.parse) attrs = this.parse(attrs, options) || {}; Daniel@0: attrs = _.defaults({}, attrs, _.result(this, 'defaults')); Daniel@0: this.set(attrs, options); Daniel@0: this.changed = {}; Daniel@0: this.initialize.apply(this, arguments); Daniel@0: }; Daniel@0: Daniel@0: // Attach all inheritable methods to the Model prototype. Daniel@0: _.extend(Model.prototype, Events, { Daniel@0: Daniel@0: // A hash of attributes whose current and previous value differ. Daniel@0: changed: null, Daniel@0: Daniel@0: // The value returned during the last failed validation. Daniel@0: validationError: null, Daniel@0: Daniel@0: // The default name for the JSON `id` attribute is `"id"`. MongoDB and Daniel@0: // CouchDB users may want to set this to `"_id"`. Daniel@0: idAttribute: 'id', Daniel@0: Daniel@0: // Initialize is an empty function by default. Override it with your own Daniel@0: // initialization logic. Daniel@0: initialize: function(){}, Daniel@0: Daniel@0: // Return a copy of the model's `attributes` object. Daniel@0: toJSON: function(options) { Daniel@0: return _.clone(this.attributes); Daniel@0: }, Daniel@0: Daniel@0: // Proxy `Backbone.sync` by default -- but override this if you need Daniel@0: // custom syncing semantics for *this* particular model. Daniel@0: sync: function() { Daniel@0: return Backbone.sync.apply(this, arguments); Daniel@0: }, Daniel@0: Daniel@0: // Get the value of an attribute. Daniel@0: get: function(attr) { Daniel@0: return this.attributes[attr]; Daniel@0: }, Daniel@0: Daniel@0: // Get the HTML-escaped value of an attribute. Daniel@0: escape: function(attr) { Daniel@0: return _.escape(this.get(attr)); Daniel@0: }, Daniel@0: Daniel@0: // Returns `true` if the attribute contains a value that is not null Daniel@0: // or undefined. Daniel@0: has: function(attr) { Daniel@0: return this.get(attr) != null; Daniel@0: }, Daniel@0: Daniel@0: // Set a hash of model attributes on the object, firing `"change"`. This is Daniel@0: // the core primitive operation of a model, updating the data and notifying Daniel@0: // anyone who needs to know about the change in state. The heart of the beast. Daniel@0: set: function(key, val, options) { Daniel@0: var attr, attrs, unset, changes, silent, changing, prev, current; Daniel@0: if (key == null) return this; Daniel@0: Daniel@0: // Handle both `"key", value` and `{key: value}` -style arguments. Daniel@0: if (typeof key === 'object') { Daniel@0: attrs = key; Daniel@0: options = val; Daniel@0: } else { Daniel@0: (attrs = {})[key] = val; Daniel@0: } Daniel@0: Daniel@0: options || (options = {}); Daniel@0: Daniel@0: // Run validation. Daniel@0: if (!this._validate(attrs, options)) return false; Daniel@0: Daniel@0: // Extract attributes and options. Daniel@0: unset = options.unset; Daniel@0: silent = options.silent; Daniel@0: changes = []; Daniel@0: changing = this._changing; Daniel@0: this._changing = true; Daniel@0: Daniel@0: if (!changing) { Daniel@0: this._previousAttributes = _.clone(this.attributes); Daniel@0: this.changed = {}; Daniel@0: } Daniel@0: current = this.attributes, prev = this._previousAttributes; Daniel@0: Daniel@0: // Check for changes of `id`. Daniel@0: if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; Daniel@0: Daniel@0: // For each `set` attribute, update or delete the current value. Daniel@0: for (attr in attrs) { Daniel@0: val = attrs[attr]; Daniel@0: if (!_.isEqual(current[attr], val)) changes.push(attr); Daniel@0: if (!_.isEqual(prev[attr], val)) { Daniel@0: this.changed[attr] = val; Daniel@0: } else { Daniel@0: delete this.changed[attr]; Daniel@0: } Daniel@0: unset ? delete current[attr] : current[attr] = val; Daniel@0: } Daniel@0: Daniel@0: // Trigger all relevant attribute changes. Daniel@0: if (!silent) { Daniel@0: if (changes.length) this._pending = options; Daniel@0: for (var i = 0, l = changes.length; i < l; i++) { Daniel@0: this.trigger('change:' + changes[i], this, current[changes[i]], options); Daniel@0: } Daniel@0: } Daniel@0: Daniel@0: // You might be wondering why there's a `while` loop here. Changes can Daniel@0: // be recursively nested within `"change"` events. Daniel@0: if (changing) return this; Daniel@0: if (!silent) { Daniel@0: while (this._pending) { Daniel@0: options = this._pending; Daniel@0: this._pending = false; Daniel@0: this.trigger('change', this, options); Daniel@0: } Daniel@0: } Daniel@0: this._pending = false; Daniel@0: this._changing = false; Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Remove an attribute from the model, firing `"change"`. `unset` is a noop Daniel@0: // if the attribute doesn't exist. Daniel@0: unset: function(attr, options) { Daniel@0: return this.set(attr, void 0, _.extend({}, options, {unset: true})); Daniel@0: }, Daniel@0: Daniel@0: // Clear all attributes on the model, firing `"change"`. Daniel@0: clear: function(options) { Daniel@0: var attrs = {}; Daniel@0: for (var key in this.attributes) attrs[key] = void 0; Daniel@0: return this.set(attrs, _.extend({}, options, {unset: true})); Daniel@0: }, Daniel@0: Daniel@0: // Determine if the model has changed since the last `"change"` event. Daniel@0: // If you specify an attribute name, determine if that attribute has changed. Daniel@0: hasChanged: function(attr) { Daniel@0: if (attr == null) return !_.isEmpty(this.changed); Daniel@0: return _.has(this.changed, attr); Daniel@0: }, Daniel@0: Daniel@0: // Return an object containing all the attributes that have changed, or Daniel@0: // false if there are no changed attributes. Useful for determining what Daniel@0: // parts of a view need to be updated and/or what attributes need to be Daniel@0: // persisted to the server. Unset attributes will be set to undefined. Daniel@0: // You can also pass an attributes object to diff against the model, Daniel@0: // determining if there *would be* a change. Daniel@0: changedAttributes: function(diff) { Daniel@0: if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; Daniel@0: var val, changed = false; Daniel@0: var old = this._changing ? this._previousAttributes : this.attributes; Daniel@0: for (var attr in diff) { Daniel@0: if (_.isEqual(old[attr], (val = diff[attr]))) continue; Daniel@0: (changed || (changed = {}))[attr] = val; Daniel@0: } Daniel@0: return changed; Daniel@0: }, Daniel@0: Daniel@0: // Get the previous value of an attribute, recorded at the time the last Daniel@0: // `"change"` event was fired. Daniel@0: previous: function(attr) { Daniel@0: if (attr == null || !this._previousAttributes) return null; Daniel@0: return this._previousAttributes[attr]; Daniel@0: }, Daniel@0: Daniel@0: // Get all of the attributes of the model at the time of the previous Daniel@0: // `"change"` event. Daniel@0: previousAttributes: function() { Daniel@0: return _.clone(this._previousAttributes); Daniel@0: }, Daniel@0: Daniel@0: // Fetch the model from the server. If the server's representation of the Daniel@0: // model differs from its current attributes, they will be overridden, Daniel@0: // triggering a `"change"` event. Daniel@0: fetch: function(options) { Daniel@0: options = options ? _.clone(options) : {}; Daniel@0: if (options.parse === void 0) options.parse = true; Daniel@0: var model = this; Daniel@0: var success = options.success; Daniel@0: options.success = function(resp) { Daniel@0: if (!model.set(model.parse(resp, options), options)) return false; Daniel@0: if (success) success(model, resp, options); Daniel@0: model.trigger('sync', model, resp, options); Daniel@0: }; Daniel@0: wrapError(this, options); Daniel@0: return this.sync('read', this, options); Daniel@0: }, Daniel@0: Daniel@0: // Set a hash of model attributes, and sync the model to the server. Daniel@0: // If the server returns an attributes hash that differs, the model's Daniel@0: // state will be `set` again. Daniel@0: save: function(key, val, options) { Daniel@0: var attrs, method, xhr, attributes = this.attributes; Daniel@0: Daniel@0: // Handle both `"key", value` and `{key: value}` -style arguments. Daniel@0: if (key == null || typeof key === 'object') { Daniel@0: attrs = key; Daniel@0: options = val; Daniel@0: } else { Daniel@0: (attrs = {})[key] = val; Daniel@0: } Daniel@0: Daniel@0: options = _.extend({validate: true}, options); Daniel@0: Daniel@0: // If we're not waiting and attributes exist, save acts as Daniel@0: // `set(attr).save(null, opts)` with validation. Otherwise, check if Daniel@0: // the model will be valid when the attributes, if any, are set. Daniel@0: if (attrs && !options.wait) { Daniel@0: if (!this.set(attrs, options)) return false; Daniel@0: } else { Daniel@0: if (!this._validate(attrs, options)) return false; Daniel@0: } Daniel@0: Daniel@0: // Set temporary attributes if `{wait: true}`. Daniel@0: if (attrs && options.wait) { Daniel@0: this.attributes = _.extend({}, attributes, attrs); Daniel@0: } Daniel@0: Daniel@0: // After a successful server-side save, the client is (optionally) Daniel@0: // updated with the server-side state. Daniel@0: if (options.parse === void 0) options.parse = true; Daniel@0: var model = this; Daniel@0: var success = options.success; Daniel@0: options.success = function(resp) { Daniel@0: // Ensure attributes are restored during synchronous saves. Daniel@0: model.attributes = attributes; Daniel@0: var serverAttrs = model.parse(resp, options); Daniel@0: if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); Daniel@0: if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { Daniel@0: return false; Daniel@0: } Daniel@0: if (success) success(model, resp, options); Daniel@0: model.trigger('sync', model, resp, options); Daniel@0: }; Daniel@0: wrapError(this, options); Daniel@0: Daniel@0: method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); Daniel@0: if (method === 'patch') options.attrs = attrs; Daniel@0: xhr = this.sync(method, this, options); Daniel@0: Daniel@0: // Restore attributes. Daniel@0: if (attrs && options.wait) this.attributes = attributes; Daniel@0: Daniel@0: return xhr; Daniel@0: }, Daniel@0: Daniel@0: // Destroy this model on the server if it was already persisted. Daniel@0: // Optimistically removes the model from its collection, if it has one. Daniel@0: // If `wait: true` is passed, waits for the server to respond before removal. Daniel@0: destroy: function(options) { Daniel@0: options = options ? _.clone(options) : {}; Daniel@0: var model = this; Daniel@0: var success = options.success; Daniel@0: Daniel@0: var destroy = function() { Daniel@0: model.trigger('destroy', model, model.collection, options); Daniel@0: }; Daniel@0: Daniel@0: options.success = function(resp) { Daniel@0: if (options.wait || model.isNew()) destroy(); Daniel@0: if (success) success(model, resp, options); Daniel@0: if (!model.isNew()) model.trigger('sync', model, resp, options); Daniel@0: }; Daniel@0: Daniel@0: if (this.isNew()) { Daniel@0: options.success(); Daniel@0: return false; Daniel@0: } Daniel@0: wrapError(this, options); Daniel@0: Daniel@0: var xhr = this.sync('delete', this, options); Daniel@0: if (!options.wait) destroy(); Daniel@0: return xhr; Daniel@0: }, Daniel@0: Daniel@0: // Default URL for the model's representation on the server -- if you're Daniel@0: // using Backbone's restful methods, override this to change the endpoint Daniel@0: // that will be called. Daniel@0: url: function() { Daniel@0: var base = Daniel@0: _.result(this, 'urlRoot') || Daniel@0: _.result(this.collection, 'url') || Daniel@0: urlError(); Daniel@0: if (this.isNew()) return base; Daniel@0: return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); Daniel@0: }, Daniel@0: Daniel@0: // **parse** converts a response into the hash of attributes to be `set` on Daniel@0: // the model. The default implementation is just to pass the response along. Daniel@0: parse: function(resp, options) { Daniel@0: return resp; Daniel@0: }, Daniel@0: Daniel@0: // Create a new model with identical attributes to this one. Daniel@0: clone: function() { Daniel@0: return new this.constructor(this.attributes); Daniel@0: }, Daniel@0: Daniel@0: // A model is new if it has never been saved to the server, and lacks an id. Daniel@0: isNew: function() { Daniel@0: return !this.has(this.idAttribute); Daniel@0: }, Daniel@0: Daniel@0: // Check if the model is currently in a valid state. Daniel@0: isValid: function(options) { Daniel@0: return this._validate({}, _.extend(options || {}, { validate: true })); Daniel@0: }, Daniel@0: Daniel@0: // Run validation against the next complete set of model attributes, Daniel@0: // returning `true` if all is well. Otherwise, fire an `"invalid"` event. Daniel@0: _validate: function(attrs, options) { Daniel@0: if (!options.validate || !this.validate) return true; Daniel@0: attrs = _.extend({}, this.attributes, attrs); Daniel@0: var error = this.validationError = this.validate(attrs, options) || null; Daniel@0: if (!error) return true; Daniel@0: this.trigger('invalid', this, error, _.extend(options, {validationError: error})); Daniel@0: return false; Daniel@0: } Daniel@0: Daniel@0: }); Daniel@0: Daniel@0: // Underscore methods that we want to implement on the Model. Daniel@0: var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; Daniel@0: Daniel@0: // Mix in each Underscore method as a proxy to `Model#attributes`. Daniel@0: _.each(modelMethods, function(method) { Daniel@0: Model.prototype[method] = function() { Daniel@0: var args = slice.call(arguments); Daniel@0: args.unshift(this.attributes); Daniel@0: return _[method].apply(_, args); Daniel@0: }; Daniel@0: }); Daniel@0: Daniel@0: // Backbone.Collection Daniel@0: // ------------------- Daniel@0: Daniel@0: // If models tend to represent a single row of data, a Backbone Collection is Daniel@0: // more analagous to a table full of data ... or a small slice or page of that Daniel@0: // table, or a collection of rows that belong together for a particular reason Daniel@0: // -- all of the messages in this particular folder, all of the documents Daniel@0: // belonging to this particular author, and so on. Collections maintain Daniel@0: // indexes of their models, both in order, and for lookup by `id`. Daniel@0: Daniel@0: // Create a new **Collection**, perhaps to contain a specific type of `model`. Daniel@0: // If a `comparator` is specified, the Collection will maintain Daniel@0: // its models in sort order, as they're added and removed. Daniel@0: var Collection = Backbone.Collection = function(models, options) { Daniel@0: options || (options = {}); Daniel@0: if (options.model) this.model = options.model; Daniel@0: if (options.comparator !== void 0) this.comparator = options.comparator; Daniel@0: this._reset(); Daniel@0: this.initialize.apply(this, arguments); Daniel@0: if (models) this.reset(models, _.extend({silent: true}, options)); Daniel@0: }; Daniel@0: Daniel@0: // Default options for `Collection#set`. Daniel@0: var setOptions = {add: true, remove: true, merge: true}; Daniel@0: var addOptions = {add: true, remove: false}; Daniel@0: Daniel@0: // Define the Collection's inheritable methods. Daniel@0: _.extend(Collection.prototype, Events, { Daniel@0: Daniel@0: // The default model for a collection is just a **Backbone.Model**. Daniel@0: // This should be overridden in most cases. Daniel@0: model: Model, Daniel@0: Daniel@0: // Initialize is an empty function by default. Override it with your own Daniel@0: // initialization logic. Daniel@0: initialize: function(){}, Daniel@0: Daniel@0: // The JSON representation of a Collection is an array of the Daniel@0: // models' attributes. Daniel@0: toJSON: function(options) { Daniel@0: return this.map(function(model){ return model.toJSON(options); }); Daniel@0: }, Daniel@0: Daniel@0: // Proxy `Backbone.sync` by default. Daniel@0: sync: function() { Daniel@0: return Backbone.sync.apply(this, arguments); Daniel@0: }, Daniel@0: Daniel@0: // Add a model, or list of models to the set. Daniel@0: add: function(models, options) { Daniel@0: return this.set(models, _.extend({merge: false}, options, addOptions)); Daniel@0: }, Daniel@0: Daniel@0: // Remove a model, or a list of models from the set. Daniel@0: remove: function(models, options) { Daniel@0: var singular = !_.isArray(models); Daniel@0: models = singular ? [models] : _.clone(models); Daniel@0: options || (options = {}); Daniel@0: var i, l, index, model; Daniel@0: for (i = 0, l = models.length; i < l; i++) { Daniel@0: model = models[i] = this.get(models[i]); Daniel@0: if (!model) continue; Daniel@0: delete this._byId[model.id]; Daniel@0: delete this._byId[model.cid]; Daniel@0: index = this.indexOf(model); Daniel@0: this.models.splice(index, 1); Daniel@0: this.length--; Daniel@0: if (!options.silent) { Daniel@0: options.index = index; Daniel@0: model.trigger('remove', model, this, options); Daniel@0: } Daniel@0: this._removeReference(model, options); Daniel@0: } Daniel@0: return singular ? models[0] : models; Daniel@0: }, Daniel@0: Daniel@0: // Update a collection by `set`-ing a new list of models, adding new ones, Daniel@0: // removing models that are no longer present, and merging models that Daniel@0: // already exist in the collection, as necessary. Similar to **Model#set**, Daniel@0: // the core operation for updating the data contained by the collection. Daniel@0: set: function(models, options) { Daniel@0: options = _.defaults({}, options, setOptions); Daniel@0: if (options.parse) models = this.parse(models, options); Daniel@0: var singular = !_.isArray(models); Daniel@0: models = singular ? (models ? [models] : []) : _.clone(models); Daniel@0: var i, l, id, model, attrs, existing, sort; Daniel@0: var at = options.at; Daniel@0: var targetModel = this.model; Daniel@0: var sortable = this.comparator && (at == null) && options.sort !== false; Daniel@0: var sortAttr = _.isString(this.comparator) ? this.comparator : null; Daniel@0: var toAdd = [], toRemove = [], modelMap = {}; Daniel@0: var add = options.add, merge = options.merge, remove = options.remove; Daniel@0: var order = !sortable && add && remove ? [] : false; Daniel@0: Daniel@0: // Turn bare objects into model references, and prevent invalid models Daniel@0: // from being added. Daniel@0: for (i = 0, l = models.length; i < l; i++) { Daniel@0: attrs = models[i] || {}; Daniel@0: if (attrs instanceof Model) { Daniel@0: id = model = attrs; Daniel@0: } else { Daniel@0: id = attrs[targetModel.prototype.idAttribute || 'id']; Daniel@0: } Daniel@0: Daniel@0: // If a duplicate is found, prevent it from being added and Daniel@0: // optionally merge it into the existing model. Daniel@0: if (existing = this.get(id)) { Daniel@0: if (remove) modelMap[existing.cid] = true; Daniel@0: if (merge) { Daniel@0: attrs = attrs === model ? model.attributes : attrs; Daniel@0: if (options.parse) attrs = existing.parse(attrs, options); Daniel@0: existing.set(attrs, options); Daniel@0: if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; Daniel@0: } Daniel@0: models[i] = existing; Daniel@0: Daniel@0: // If this is a new, valid model, push it to the `toAdd` list. Daniel@0: } else if (add) { Daniel@0: model = models[i] = this._prepareModel(attrs, options); Daniel@0: if (!model) continue; Daniel@0: toAdd.push(model); Daniel@0: this._addReference(model, options); Daniel@0: } Daniel@0: Daniel@0: // Do not add multiple models with the same `id`. Daniel@0: model = existing || model; Daniel@0: if (order && (model.isNew() || !modelMap[model.id])) order.push(model); Daniel@0: modelMap[model.id] = true; Daniel@0: } Daniel@0: Daniel@0: // Remove nonexistent models if appropriate. Daniel@0: if (remove) { Daniel@0: for (i = 0, l = this.length; i < l; ++i) { Daniel@0: if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); Daniel@0: } Daniel@0: if (toRemove.length) this.remove(toRemove, options); Daniel@0: } Daniel@0: Daniel@0: // See if sorting is needed, update `length` and splice in new models. Daniel@0: if (toAdd.length || (order && order.length)) { Daniel@0: if (sortable) sort = true; Daniel@0: this.length += toAdd.length; Daniel@0: if (at != null) { Daniel@0: for (i = 0, l = toAdd.length; i < l; i++) { Daniel@0: this.models.splice(at + i, 0, toAdd[i]); Daniel@0: } Daniel@0: } else { Daniel@0: if (order) this.models.length = 0; Daniel@0: var orderedModels = order || toAdd; Daniel@0: for (i = 0, l = orderedModels.length; i < l; i++) { Daniel@0: this.models.push(orderedModels[i]); Daniel@0: } Daniel@0: } Daniel@0: } Daniel@0: Daniel@0: // Silently sort the collection if appropriate. Daniel@0: if (sort) this.sort({silent: true}); Daniel@0: Daniel@0: // Unless silenced, it's time to fire all appropriate add/sort events. Daniel@0: if (!options.silent) { Daniel@0: for (i = 0, l = toAdd.length; i < l; i++) { Daniel@0: (model = toAdd[i]).trigger('add', model, this, options); Daniel@0: } Daniel@0: if (sort || (order && order.length)) this.trigger('sort', this, options); Daniel@0: } Daniel@0: Daniel@0: // Return the added (or merged) model (or models). Daniel@0: return singular ? models[0] : models; Daniel@0: }, Daniel@0: Daniel@0: // When you have more items than you want to add or remove individually, Daniel@0: // you can reset the entire set with a new list of models, without firing Daniel@0: // any granular `add` or `remove` events. Fires `reset` when finished. Daniel@0: // Useful for bulk operations and optimizations. Daniel@0: reset: function(models, options) { Daniel@0: options || (options = {}); Daniel@0: for (var i = 0, l = this.models.length; i < l; i++) { Daniel@0: this._removeReference(this.models[i], options); Daniel@0: } Daniel@0: options.previousModels = this.models; Daniel@0: this._reset(); Daniel@0: models = this.add(models, _.extend({silent: true}, options)); Daniel@0: if (!options.silent) this.trigger('reset', this, options); Daniel@0: return models; Daniel@0: }, Daniel@0: Daniel@0: // Add a model to the end of the collection. Daniel@0: push: function(model, options) { Daniel@0: return this.add(model, _.extend({at: this.length}, options)); Daniel@0: }, Daniel@0: Daniel@0: // Remove a model from the end of the collection. Daniel@0: pop: function(options) { Daniel@0: var model = this.at(this.length - 1); Daniel@0: this.remove(model, options); Daniel@0: return model; Daniel@0: }, Daniel@0: Daniel@0: // Add a model to the beginning of the collection. Daniel@0: unshift: function(model, options) { Daniel@0: return this.add(model, _.extend({at: 0}, options)); Daniel@0: }, Daniel@0: Daniel@0: // Remove a model from the beginning of the collection. Daniel@0: shift: function(options) { Daniel@0: var model = this.at(0); Daniel@0: this.remove(model, options); Daniel@0: return model; Daniel@0: }, Daniel@0: Daniel@0: // Slice out a sub-array of models from the collection. Daniel@0: slice: function() { Daniel@0: return slice.apply(this.models, arguments); Daniel@0: }, Daniel@0: Daniel@0: // Get a model from the set by id. Daniel@0: get: function(obj) { Daniel@0: if (obj == null) return void 0; Daniel@0: return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid]; Daniel@0: }, Daniel@0: Daniel@0: // Get the model at the given index. Daniel@0: at: function(index) { Daniel@0: return this.models[index]; Daniel@0: }, Daniel@0: Daniel@0: // Return models with matching attributes. Useful for simple cases of Daniel@0: // `filter`. Daniel@0: where: function(attrs, first) { Daniel@0: if (_.isEmpty(attrs)) return first ? void 0 : []; Daniel@0: return this[first ? 'find' : 'filter'](function(model) { Daniel@0: for (var key in attrs) { Daniel@0: if (attrs[key] !== model.get(key)) return false; Daniel@0: } Daniel@0: return true; Daniel@0: }); Daniel@0: }, Daniel@0: Daniel@0: // Return the first model with matching attributes. Useful for simple cases Daniel@0: // of `find`. Daniel@0: findWhere: function(attrs) { Daniel@0: return this.where(attrs, true); Daniel@0: }, Daniel@0: Daniel@0: // Force the collection to re-sort itself. You don't need to call this under Daniel@0: // normal circumstances, as the set will maintain sort order as each item Daniel@0: // is added. Daniel@0: sort: function(options) { Daniel@0: if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); Daniel@0: options || (options = {}); Daniel@0: Daniel@0: // Run sort based on type of `comparator`. Daniel@0: if (_.isString(this.comparator) || this.comparator.length === 1) { Daniel@0: this.models = this.sortBy(this.comparator, this); Daniel@0: } else { Daniel@0: this.models.sort(_.bind(this.comparator, this)); Daniel@0: } Daniel@0: Daniel@0: if (!options.silent) this.trigger('sort', this, options); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Pluck an attribute from each model in the collection. Daniel@0: pluck: function(attr) { Daniel@0: return _.invoke(this.models, 'get', attr); Daniel@0: }, Daniel@0: Daniel@0: // Fetch the default set of models for this collection, resetting the Daniel@0: // collection when they arrive. If `reset: true` is passed, the response Daniel@0: // data will be passed through the `reset` method instead of `set`. Daniel@0: fetch: function(options) { Daniel@0: options = options ? _.clone(options) : {}; Daniel@0: if (options.parse === void 0) options.parse = true; Daniel@0: var success = options.success; Daniel@0: var collection = this; Daniel@0: options.success = function(resp) { Daniel@0: var method = options.reset ? 'reset' : 'set'; Daniel@0: collection[method](resp, options); Daniel@0: if (success) success(collection, resp, options); Daniel@0: collection.trigger('sync', collection, resp, options); Daniel@0: }; Daniel@0: wrapError(this, options); Daniel@0: return this.sync('read', this, options); Daniel@0: }, Daniel@0: Daniel@0: // Create a new instance of a model in this collection. Add the model to the Daniel@0: // collection immediately, unless `wait: true` is passed, in which case we Daniel@0: // wait for the server to agree. Daniel@0: create: function(model, options) { Daniel@0: options = options ? _.clone(options) : {}; Daniel@0: if (!(model = this._prepareModel(model, options))) return false; Daniel@0: if (!options.wait) this.add(model, options); Daniel@0: var collection = this; Daniel@0: var success = options.success; Daniel@0: options.success = function(model, resp) { Daniel@0: if (options.wait) collection.add(model, options); Daniel@0: if (success) success(model, resp, options); Daniel@0: }; Daniel@0: model.save(null, options); Daniel@0: return model; Daniel@0: }, Daniel@0: Daniel@0: // **parse** converts a response into a list of models to be added to the Daniel@0: // collection. The default implementation is just to pass it through. Daniel@0: parse: function(resp, options) { Daniel@0: return resp; Daniel@0: }, Daniel@0: Daniel@0: // Create a new collection with an identical list of models as this one. Daniel@0: clone: function() { Daniel@0: return new this.constructor(this.models); Daniel@0: }, Daniel@0: Daniel@0: // Private method to reset all internal state. Called when the collection Daniel@0: // is first initialized or reset. Daniel@0: _reset: function() { Daniel@0: this.length = 0; Daniel@0: this.models = []; Daniel@0: this._byId = {}; Daniel@0: }, Daniel@0: Daniel@0: // Prepare a hash of attributes (or other model) to be added to this Daniel@0: // collection. Daniel@0: _prepareModel: function(attrs, options) { Daniel@0: if (attrs instanceof Model) return attrs; Daniel@0: options = options ? _.clone(options) : {}; Daniel@0: options.collection = this; Daniel@0: var model = new this.model(attrs, options); Daniel@0: if (!model.validationError) return model; Daniel@0: this.trigger('invalid', this, model.validationError, options); Daniel@0: return false; Daniel@0: }, Daniel@0: Daniel@0: // Internal method to create a model's ties to a collection. Daniel@0: _addReference: function(model, options) { Daniel@0: this._byId[model.cid] = model; Daniel@0: if (model.id != null) this._byId[model.id] = model; Daniel@0: if (!model.collection) model.collection = this; Daniel@0: model.on('all', this._onModelEvent, this); Daniel@0: }, Daniel@0: Daniel@0: // Internal method to sever a model's ties to a collection. Daniel@0: _removeReference: function(model, options) { Daniel@0: if (this === model.collection) delete model.collection; Daniel@0: model.off('all', this._onModelEvent, this); Daniel@0: }, Daniel@0: Daniel@0: // Internal method called every time a model in the set fires an event. Daniel@0: // Sets need to update their indexes when models change ids. All other Daniel@0: // events simply proxy through. "add" and "remove" events that originate Daniel@0: // in other collections are ignored. Daniel@0: _onModelEvent: function(event, model, collection, options) { Daniel@0: if ((event === 'add' || event === 'remove') && collection !== this) return; Daniel@0: if (event === 'destroy') this.remove(model, options); Daniel@0: if (model && event === 'change:' + model.idAttribute) { Daniel@0: delete this._byId[model.previous(model.idAttribute)]; Daniel@0: if (model.id != null) this._byId[model.id] = model; Daniel@0: } Daniel@0: this.trigger.apply(this, arguments); Daniel@0: } Daniel@0: Daniel@0: }); Daniel@0: Daniel@0: // Underscore methods that we want to implement on the Collection. Daniel@0: // 90% of the core usefulness of Backbone Collections is actually implemented Daniel@0: // right here: Daniel@0: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', Daniel@0: 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', Daniel@0: 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', Daniel@0: 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', Daniel@0: 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', Daniel@0: 'lastIndexOf', 'isEmpty', 'chain', 'sample']; Daniel@0: Daniel@0: // Mix in each Underscore method as a proxy to `Collection#models`. Daniel@0: _.each(methods, function(method) { Daniel@0: Collection.prototype[method] = function() { Daniel@0: var args = slice.call(arguments); Daniel@0: args.unshift(this.models); Daniel@0: return _[method].apply(_, args); Daniel@0: }; Daniel@0: }); Daniel@0: Daniel@0: // Underscore methods that take a property name as an argument. Daniel@0: var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; Daniel@0: Daniel@0: // Use attributes instead of properties. Daniel@0: _.each(attributeMethods, function(method) { Daniel@0: Collection.prototype[method] = function(value, context) { Daniel@0: var iterator = _.isFunction(value) ? value : function(model) { Daniel@0: return model.get(value); Daniel@0: }; Daniel@0: return _[method](this.models, iterator, context); Daniel@0: }; Daniel@0: }); Daniel@0: Daniel@0: // Backbone.View Daniel@0: // ------------- Daniel@0: Daniel@0: // Backbone Views are almost more convention than they are actual code. A View Daniel@0: // is simply a JavaScript object that represents a logical chunk of UI in the Daniel@0: // DOM. This might be a single item, an entire list, a sidebar or panel, or Daniel@0: // even the surrounding frame which wraps your whole app. Defining a chunk of Daniel@0: // UI as a **View** allows you to define your DOM events declaratively, without Daniel@0: // having to worry about render order ... and makes it easy for the view to Daniel@0: // react to specific changes in the state of your models. Daniel@0: Daniel@0: // Creating a Backbone.View creates its initial element outside of the DOM, Daniel@0: // if an existing element is not provided... Daniel@0: var View = Backbone.View = function(options) { Daniel@0: this.cid = _.uniqueId('view'); Daniel@0: options || (options = {}); Daniel@0: _.extend(this, _.pick(options, viewOptions)); Daniel@0: this._ensureElement(); Daniel@0: this.initialize.apply(this, arguments); Daniel@0: this.delegateEvents(); Daniel@0: }; Daniel@0: Daniel@0: // Cached regex to split keys for `delegate`. Daniel@0: var delegateEventSplitter = /^(\S+)\s*(.*)$/; Daniel@0: Daniel@0: // List of view options to be merged as properties. Daniel@0: var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; Daniel@0: Daniel@0: // Set up all inheritable **Backbone.View** properties and methods. Daniel@0: _.extend(View.prototype, Events, { Daniel@0: Daniel@0: // The default `tagName` of a View's element is `"div"`. Daniel@0: tagName: 'div', Daniel@0: Daniel@0: // jQuery delegate for element lookup, scoped to DOM elements within the Daniel@0: // current view. This should be preferred to global lookups where possible. Daniel@0: $: function(selector) { Daniel@0: return this.$el.find(selector); Daniel@0: }, Daniel@0: Daniel@0: // Initialize is an empty function by default. Override it with your own Daniel@0: // initialization logic. Daniel@0: initialize: function(){}, Daniel@0: Daniel@0: // **render** is the core function that your view should override, in order Daniel@0: // to populate its element (`this.el`), with the appropriate HTML. The Daniel@0: // convention is for **render** to always return `this`. Daniel@0: render: function() { Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Remove this view by taking the element out of the DOM, and removing any Daniel@0: // applicable Backbone.Events listeners. Daniel@0: remove: function() { Daniel@0: this.$el.remove(); Daniel@0: this.stopListening(); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Change the view's element (`this.el` property), including event Daniel@0: // re-delegation. Daniel@0: setElement: function(element, delegate) { Daniel@0: if (this.$el) this.undelegateEvents(); Daniel@0: this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); Daniel@0: this.el = this.$el[0]; Daniel@0: if (delegate !== false) this.delegateEvents(); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Set callbacks, where `this.events` is a hash of Daniel@0: // Daniel@0: // *{"event selector": "callback"}* Daniel@0: // Daniel@0: // { Daniel@0: // 'mousedown .title': 'edit', Daniel@0: // 'click .button': 'save', Daniel@0: // 'click .open': function(e) { ... } Daniel@0: // } Daniel@0: // Daniel@0: // pairs. Callbacks will be bound to the view, with `this` set properly. Daniel@0: // Uses event delegation for efficiency. Daniel@0: // Omitting the selector binds the event to `this.el`. Daniel@0: // This only works for delegate-able events: not `focus`, `blur`, and Daniel@0: // not `change`, `submit`, and `reset` in Internet Explorer. Daniel@0: delegateEvents: function(events) { Daniel@0: if (!(events || (events = _.result(this, 'events')))) return this; Daniel@0: this.undelegateEvents(); Daniel@0: for (var key in events) { Daniel@0: var method = events[key]; Daniel@0: if (!_.isFunction(method)) method = this[events[key]]; Daniel@0: if (!method) continue; Daniel@0: Daniel@0: var match = key.match(delegateEventSplitter); Daniel@0: var eventName = match[1], selector = match[2]; Daniel@0: method = _.bind(method, this); Daniel@0: eventName += '.delegateEvents' + this.cid; Daniel@0: if (selector === '') { Daniel@0: this.$el.on(eventName, method); Daniel@0: } else { Daniel@0: this.$el.on(eventName, selector, method); Daniel@0: } Daniel@0: } Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Clears all callbacks previously bound to the view with `delegateEvents`. Daniel@0: // You usually don't need to use this, but may wish to if you have multiple Daniel@0: // Backbone views attached to the same DOM element. Daniel@0: undelegateEvents: function() { Daniel@0: this.$el.off('.delegateEvents' + this.cid); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Ensure that the View has a DOM element to render into. Daniel@0: // If `this.el` is a string, pass it through `$()`, take the first Daniel@0: // matching element, and re-assign it to `el`. Otherwise, create Daniel@0: // an element from the `id`, `className` and `tagName` properties. Daniel@0: _ensureElement: function() { Daniel@0: if (!this.el) { Daniel@0: var attrs = _.extend({}, _.result(this, 'attributes')); Daniel@0: if (this.id) attrs.id = _.result(this, 'id'); Daniel@0: if (this.className) attrs['class'] = _.result(this, 'className'); Daniel@0: var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); Daniel@0: this.setElement($el, false); Daniel@0: } else { Daniel@0: this.setElement(_.result(this, 'el'), false); Daniel@0: } Daniel@0: } Daniel@0: Daniel@0: }); Daniel@0: Daniel@0: // Backbone.sync Daniel@0: // ------------- Daniel@0: Daniel@0: // Override this function to change the manner in which Backbone persists Daniel@0: // models to the server. You will be passed the type of request, and the Daniel@0: // model in question. By default, makes a RESTful Ajax request Daniel@0: // to the model's `url()`. Some possible customizations could be: Daniel@0: // Daniel@0: // * Use `setTimeout` to batch rapid-fire updates into a single request. Daniel@0: // * Send up the models as XML instead of JSON. Daniel@0: // * Persist models via WebSockets instead of Ajax. Daniel@0: // Daniel@0: // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests Daniel@0: // as `POST`, with a `_method` parameter containing the true HTTP method, Daniel@0: // as well as all requests with the body as `application/x-www-form-urlencoded` Daniel@0: // instead of `application/json` with the model in a param named `model`. Daniel@0: // Useful when interfacing with server-side languages like **PHP** that make Daniel@0: // it difficult to read the body of `PUT` requests. Daniel@0: Backbone.sync = function(method, model, options) { Daniel@0: var type = methodMap[method]; Daniel@0: Daniel@0: // Default options, unless specified. Daniel@0: _.defaults(options || (options = {}), { Daniel@0: emulateHTTP: Backbone.emulateHTTP, Daniel@0: emulateJSON: Backbone.emulateJSON Daniel@0: }); Daniel@0: Daniel@0: // Default JSON-request options. Daniel@0: var params = {type: type, dataType: 'json'}; Daniel@0: Daniel@0: // Ensure that we have a URL. Daniel@0: if (!options.url) { Daniel@0: params.url = _.result(model, 'url') || urlError(); Daniel@0: } Daniel@0: Daniel@0: // Ensure that we have the appropriate request data. Daniel@0: if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { Daniel@0: params.contentType = 'application/json'; Daniel@0: params.data = JSON.stringify(options.attrs || model.toJSON(options)); Daniel@0: } Daniel@0: Daniel@0: // For older servers, emulate JSON by encoding the request into an HTML-form. Daniel@0: if (options.emulateJSON) { Daniel@0: params.contentType = 'application/x-www-form-urlencoded'; Daniel@0: params.data = params.data ? {model: params.data} : {}; Daniel@0: } Daniel@0: Daniel@0: // For older servers, emulate HTTP by mimicking the HTTP method with `_method` Daniel@0: // And an `X-HTTP-Method-Override` header. Daniel@0: if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { Daniel@0: params.type = 'POST'; Daniel@0: if (options.emulateJSON) params.data._method = type; Daniel@0: var beforeSend = options.beforeSend; Daniel@0: options.beforeSend = function(xhr) { Daniel@0: xhr.setRequestHeader('X-HTTP-Method-Override', type); Daniel@0: if (beforeSend) return beforeSend.apply(this, arguments); Daniel@0: }; Daniel@0: } Daniel@0: Daniel@0: // Don't process data on a non-GET request. Daniel@0: if (params.type !== 'GET' && !options.emulateJSON) { Daniel@0: params.processData = false; Daniel@0: } Daniel@0: Daniel@0: // If we're sending a `PATCH` request, and we're in an old Internet Explorer Daniel@0: // that still has ActiveX enabled by default, override jQuery to use that Daniel@0: // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. Daniel@0: if (params.type === 'PATCH' && noXhrPatch) { Daniel@0: params.xhr = function() { Daniel@0: return new ActiveXObject("Microsoft.XMLHTTP"); Daniel@0: }; Daniel@0: } Daniel@0: Daniel@0: // Make the request, allowing the user to override any Ajax options. Daniel@0: var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); Daniel@0: model.trigger('request', model, xhr, options); Daniel@0: return xhr; Daniel@0: }; Daniel@0: Daniel@0: var noXhrPatch = Daniel@0: typeof window !== 'undefined' && !!window.ActiveXObject && Daniel@0: !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); Daniel@0: Daniel@0: // Map from CRUD to HTTP for our default `Backbone.sync` implementation. Daniel@0: var methodMap = { Daniel@0: 'create': 'POST', Daniel@0: 'update': 'PUT', Daniel@0: 'patch': 'PATCH', Daniel@0: 'delete': 'DELETE', Daniel@0: 'read': 'GET' Daniel@0: }; Daniel@0: Daniel@0: // Set the default implementation of `Backbone.ajax` to proxy through to `$`. Daniel@0: // Override this if you'd like to use a different library. Daniel@0: Backbone.ajax = function() { Daniel@0: return Backbone.$.ajax.apply(Backbone.$, arguments); Daniel@0: }; Daniel@0: Daniel@0: // Backbone.Router Daniel@0: // --------------- Daniel@0: Daniel@0: // Routers map faux-URLs to actions, and fire events when routes are Daniel@0: // matched. Creating a new one sets its `routes` hash, if not set statically. Daniel@0: var Router = Backbone.Router = function(options) { Daniel@0: options || (options = {}); Daniel@0: if (options.routes) this.routes = options.routes; Daniel@0: this._bindRoutes(); Daniel@0: this.initialize.apply(this, arguments); Daniel@0: }; Daniel@0: Daniel@0: // Cached regular expressions for matching named param parts and splatted Daniel@0: // parts of route strings. Daniel@0: var optionalParam = /\((.*?)\)/g; Daniel@0: var namedParam = /(\(\?)?:\w+/g; Daniel@0: var splatParam = /\*\w+/g; Daniel@0: var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; Daniel@0: Daniel@0: // Set up all inheritable **Backbone.Router** properties and methods. Daniel@0: _.extend(Router.prototype, Events, { Daniel@0: Daniel@0: // Initialize is an empty function by default. Override it with your own Daniel@0: // initialization logic. Daniel@0: initialize: function(){}, Daniel@0: Daniel@0: // Manually bind a single named route to a callback. For example: Daniel@0: // Daniel@0: // this.route('search/:query/p:num', 'search', function(query, num) { Daniel@0: // ... Daniel@0: // }); Daniel@0: // Daniel@0: route: function(route, name, callback) { Daniel@0: if (!_.isRegExp(route)) route = this._routeToRegExp(route); Daniel@0: if (_.isFunction(name)) { Daniel@0: callback = name; Daniel@0: name = ''; Daniel@0: } Daniel@0: if (!callback) callback = this[name]; Daniel@0: var router = this; Daniel@0: Backbone.history.route(route, function(fragment) { Daniel@0: var args = router._extractParameters(route, fragment); Daniel@0: router.execute(callback, args); Daniel@0: router.trigger.apply(router, ['route:' + name].concat(args)); Daniel@0: router.trigger('route', name, args); Daniel@0: Backbone.history.trigger('route', router, name, args); Daniel@0: }); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Execute a route handler with the provided parameters. This is an Daniel@0: // excellent place to do pre-route setup or post-route cleanup. Daniel@0: execute: function(callback, args) { Daniel@0: if (callback) callback.apply(this, args); Daniel@0: }, Daniel@0: Daniel@0: // Simple proxy to `Backbone.history` to save a fragment into the history. Daniel@0: navigate: function(fragment, options) { Daniel@0: Backbone.history.navigate(fragment, options); Daniel@0: return this; Daniel@0: }, Daniel@0: Daniel@0: // Bind all defined routes to `Backbone.history`. We have to reverse the Daniel@0: // order of the routes here to support behavior where the most general Daniel@0: // routes can be defined at the bottom of the route map. Daniel@0: _bindRoutes: function() { Daniel@0: if (!this.routes) return; Daniel@0: this.routes = _.result(this, 'routes'); Daniel@0: var route, routes = _.keys(this.routes); Daniel@0: while ((route = routes.pop()) != null) { Daniel@0: this.route(route, this.routes[route]); Daniel@0: } Daniel@0: }, Daniel@0: Daniel@0: // Convert a route string into a regular expression, suitable for matching Daniel@0: // against the current location hash. Daniel@0: _routeToRegExp: function(route) { Daniel@0: route = route.replace(escapeRegExp, '\\$&') Daniel@0: .replace(optionalParam, '(?:$1)?') Daniel@0: .replace(namedParam, function(match, optional) { Daniel@0: return optional ? match : '([^/?]+)'; Daniel@0: }) Daniel@0: .replace(splatParam, '([^?]*?)'); Daniel@0: return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); Daniel@0: }, Daniel@0: Daniel@0: // Given a route, and a URL fragment that it matches, return the array of Daniel@0: // extracted decoded parameters. Empty or unmatched parameters will be Daniel@0: // treated as `null` to normalize cross-browser behavior. Daniel@0: _extractParameters: function(route, fragment) { Daniel@0: var params = route.exec(fragment).slice(1); Daniel@0: return _.map(params, function(param, i) { Daniel@0: // Don't decode the search params. Daniel@0: if (i === params.length - 1) return param || null; Daniel@0: return param ? decodeURIComponent(param) : null; Daniel@0: }); Daniel@0: } Daniel@0: Daniel@0: }); Daniel@0: Daniel@0: // Backbone.History Daniel@0: // ---------------- Daniel@0: Daniel@0: // Handles cross-browser history management, based on either Daniel@0: // [pushState](http://diveintohtml5.info/history.html) and real URLs, or Daniel@0: // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) Daniel@0: // and URL fragments. If the browser supports neither (old IE, natch), Daniel@0: // falls back to polling. Daniel@0: var History = Backbone.History = function() { Daniel@0: this.handlers = []; Daniel@0: _.bindAll(this, 'checkUrl'); Daniel@0: Daniel@0: // Ensure that `History` can be used outside of the browser. Daniel@0: if (typeof window !== 'undefined') { Daniel@0: this.location = window.location; Daniel@0: this.history = window.history; Daniel@0: } Daniel@0: }; Daniel@0: Daniel@0: // Cached regex for stripping a leading hash/slash and trailing space. Daniel@0: var routeStripper = /^[#\/]|\s+$/g; Daniel@0: Daniel@0: // Cached regex for stripping leading and trailing slashes. Daniel@0: var rootStripper = /^\/+|\/+$/g; Daniel@0: Daniel@0: // Cached regex for detecting MSIE. Daniel@0: var isExplorer = /msie [\w.]+/; Daniel@0: Daniel@0: // Cached regex for removing a trailing slash. Daniel@0: var trailingSlash = /\/$/; Daniel@0: Daniel@0: // Cached regex for stripping urls of hash. Daniel@0: var pathStripper = /#.*$/; Daniel@0: Daniel@0: // Has the history handling already been started? Daniel@0: History.started = false; Daniel@0: Daniel@0: // Set up all inheritable **Backbone.History** properties and methods. Daniel@0: _.extend(History.prototype, Events, { Daniel@0: Daniel@0: // The default interval to poll for hash changes, if necessary, is Daniel@0: // twenty times a second. Daniel@0: interval: 50, Daniel@0: Daniel@0: // Are we at the app root? Daniel@0: atRoot: function() { Daniel@0: return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root; Daniel@0: }, Daniel@0: Daniel@0: // Gets the true hash value. Cannot use location.hash directly due to bug Daniel@0: // in Firefox where location.hash will always be decoded. Daniel@0: getHash: function(window) { Daniel@0: var match = (window || this).location.href.match(/#(.*)$/); Daniel@0: return match ? match[1] : ''; Daniel@0: }, Daniel@0: Daniel@0: // Get the cross-browser normalized URL fragment, either from the URL, Daniel@0: // the hash, or the override. Daniel@0: getFragment: function(fragment, forcePushState) { Daniel@0: if (fragment == null) { Daniel@0: if (this._hasPushState || !this._wantsHashChange || forcePushState) { Daniel@0: fragment = decodeURI(this.location.pathname + this.location.search); Daniel@0: var root = this.root.replace(trailingSlash, ''); Daniel@0: if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); Daniel@0: } else { Daniel@0: fragment = this.getHash(); Daniel@0: } Daniel@0: } Daniel@0: return fragment.replace(routeStripper, ''); Daniel@0: }, Daniel@0: Daniel@0: // Start the hash change handling, returning `true` if the current URL matches Daniel@0: // an existing route, and `false` otherwise. Daniel@0: start: function(options) { Daniel@0: if (History.started) throw new Error("Backbone.history has already been started"); Daniel@0: History.started = true; Daniel@0: Daniel@0: // Figure out the initial configuration. Do we need an iframe? Daniel@0: // Is pushState desired ... is it available? Daniel@0: this.options = _.extend({root: '/'}, this.options, options); Daniel@0: this.root = this.options.root; Daniel@0: this._wantsHashChange = this.options.hashChange !== false; Daniel@0: this._wantsPushState = !!this.options.pushState; Daniel@0: this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); Daniel@0: var fragment = this.getFragment(); Daniel@0: var docMode = document.documentMode; Daniel@0: var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); Daniel@0: Daniel@0: // Normalize root to always include a leading and trailing slash. Daniel@0: this.root = ('/' + this.root + '/').replace(rootStripper, '/'); Daniel@0: Daniel@0: if (oldIE && this._wantsHashChange) { Daniel@0: var frame = Backbone.$('