backbone.js (lodash-4.0.0) | : | backbone.js (lodash-4.17.21) | ||
---|---|---|---|---|
// Backbone.js 1.2.3 | // Backbone.js 1.3.3 | |||
// (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors | // (c) 2010-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors | |||
// Backbone may be freely distributed under the MIT license. | // Backbone may be freely distributed under the MIT license. | |||
// For all details and documentation: | // For all details and documentation: | |||
// http://backbonejs.org | // http://backbonejs.org | |||
(function(factory) { | (function(factory) { | |||
// Establish the root object, `window` (`self`) in the browser, or `global` on the server. | // Establish the root object, `window` (`self`) in the browser, or `global` on the server. | |||
// We use `self` instead of `window` for `WebWorker` support. | // We use `self` instead of `window` for `WebWorker` support. | |||
var root = (typeof self == 'object' && self.self == self && self) || | var root = (typeof self == 'object' && self.self === self && self) || | |||
(typeof global == 'object' && global.global == global && global); | (typeof global == 'object' && global.global === global && global); | |||
// Set up Backbone appropriately for the environment. Start with AMD. | // Set up Backbone appropriately for the environment. Start with AMD. | |||
if (typeof define === 'function' && define.amd) { | if (typeof define === 'function' && define.amd) { | |||
define(['underscore', 'jquery', 'exports'], function(_, $, exports) { | define(['underscore', 'jquery', 'exports'], function(_, $, exports) { | |||
// Export global even in AMD case in case this script is loaded with | // Export global even in AMD case in case this script is loaded with | |||
// others that may still expect a global Backbone. | // others that may still expect a global Backbone. | |||
root.Backbone = factory(root, exports, _, $); | root.Backbone = factory(root, exports, _, $); | |||
}); | }); | |||
// Next for Node.js or CommonJS. jQuery may not be needed as a module. | // Next for Node.js or CommonJS. jQuery may not be needed as a module. | |||
skipping to change at line 47 | skipping to change at line 47 | |||
// ------------- | // ------------- | |||
// Save the previous value of the `Backbone` variable, so that it can be | // Save the previous value of the `Backbone` variable, so that it can be | |||
// restored later on, if `noConflict` is used. | // restored later on, if `noConflict` is used. | |||
var previousBackbone = root.Backbone; | var previousBackbone = root.Backbone; | |||
// Create a local reference to a common array method we'll want to use later. | // Create a local reference to a common array method we'll want to use later. | |||
var slice = Array.prototype.slice; | var slice = Array.prototype.slice; | |||
// Current version of the library. Keep in sync with `package.json`. | // Current version of the library. Keep in sync with `package.json`. | |||
Backbone.VERSION = '1.2.3'; | Backbone.VERSION = '1.3.3'; | |||
// For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns | // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns | |||
// the `$` variable. | // the `$` variable. | |||
Backbone.$ = $; | Backbone.$ = $; | |||
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable | |||
// to its previous owner. Returns a reference to this Backbone object. | // to its previous owner. Returns a reference to this Backbone object. | |||
Backbone.noConflict = function() { | Backbone.noConflict = function() { | |||
root.Backbone = previousBackbone; | root.Backbone = previousBackbone; | |||
return this; | return this; | |||
skipping to change at line 149 | skipping to change at line 149 | |||
// maps `{event: callback}`). | // maps `{event: callback}`). | |||
var eventsApi = function(iteratee, events, name, callback, opts) { | var eventsApi = function(iteratee, events, name, callback, opts) { | |||
var i = 0, names; | var i = 0, names; | |||
if (name && typeof name === 'object') { | if (name && typeof name === 'object') { | |||
// Handle event maps. | // Handle event maps. | |||
if (callback !== void 0 && 'context' in opts && opts.context === void 0) o pts.context = callback; | if (callback !== void 0 && 'context' in opts && opts.context === void 0) o pts.context = callback; | |||
for (names = _.keys(name); i < names.length ; i++) { | for (names = _.keys(name); i < names.length ; i++) { | |||
events = eventsApi(iteratee, events, names[i], name[names[i]], opts); | events = eventsApi(iteratee, events, names[i], name[names[i]], opts); | |||
} | } | |||
} else if (name && eventSplitter.test(name)) { | } else if (name && eventSplitter.test(name)) { | |||
// Handle space separated event names by delegating them individually. | // Handle space-separated event names by delegating them individually. | |||
for (names = name.split(eventSplitter); i < names.length; i++) { | for (names = name.split(eventSplitter); i < names.length; i++) { | |||
events = iteratee(events, names[i], callback, opts); | events = iteratee(events, names[i], callback, opts); | |||
} | } | |||
} else { | } else { | |||
// Finally, standard events. | // Finally, standard events. | |||
events = iteratee(events, name, callback, opts); | events = iteratee(events, name, callback, opts); | |||
} | } | |||
return events; | return events; | |||
}; | }; | |||
skipping to change at line 245 | skipping to change at line 245 | |||
for (var i = 0; i < ids.length; i++) { | for (var i = 0; i < ids.length; i++) { | |||
var listening = listeningTo[ids[i]]; | var listening = listeningTo[ids[i]]; | |||
// If listening doesn't exist, this object is not currently | // If listening doesn't exist, this object is not currently | |||
// listening to obj. Break out early. | // listening to obj. Break out early. | |||
if (!listening) break; | if (!listening) break; | |||
listening.obj.off(name, callback, this); | listening.obj.off(name, callback, this); | |||
} | } | |||
if (_.isEmpty(listeningTo)) this._listeningTo = void 0; | ||||
return this; | return this; | |||
}; | }; | |||
// The reducing API that removes a callback from the `events` object. | // The reducing API that removes a callback from the `events` object. | |||
var offApi = function(events, name, callback, options) { | var offApi = function(events, name, callback, options) { | |||
if (!events) return; | if (!events) return; | |||
var i = 0, listening; | var i = 0, listening; | |||
var context = options.context, listeners = options.listeners; | var context = options.context, listeners = options.listeners; | |||
skipping to change at line 302 | skipping to change at line 301 | |||
} | } | |||
} | } | |||
// Update tail event if the list has any events. Otherwise, clean up. | // Update tail event if the list has any events. Otherwise, clean up. | |||
if (remaining.length) { | if (remaining.length) { | |||
events[name] = remaining; | events[name] = remaining; | |||
} else { | } else { | |||
delete events[name]; | delete events[name]; | |||
} | } | |||
} | } | |||
if (_.size(events)) return events; | return events; | |||
}; | }; | |||
// Bind an event to only be triggered a single time. After the first time | // Bind an event to only be triggered a single time. After the first time | |||
// the callback is invoked, its listener will be removed. If multiple events | // the callback is invoked, its listener will be removed. If multiple events | |||
// are passed in using the space-separated syntax, the handler will fire | // are passed in using the space-separated syntax, the handler will fire | |||
// once for each event, not once for a combination of all events. | // once for each event, not once for a combination of all events. | |||
Events.once = function(name, callback, context) { | Events.once = function(name, callback, context) { | |||
// Map the event into a `{event: once}` object. | // Map the event into a `{event: once}` object. | |||
var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this)); | var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this)); | |||
return this.on(events, void 0, context); | if (typeof name === 'string' && context == null) callback = void 0; | |||
return this.on(events, callback, context); | ||||
}; | }; | |||
// Inversion-of-control versions of `once`. | // Inversion-of-control versions of `once`. | |||
Events.listenToOnce = function(obj, name, callback) { | Events.listenToOnce = function(obj, name, callback) { | |||
// Map the event into a `{event: once}` object. | // Map the event into a `{event: once}` object. | |||
var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListenin g, this, obj)); | var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListenin g, this, obj)); | |||
return this.listenTo(obj, events); | return this.listenTo(obj, events); | |||
}; | }; | |||
// Reduces the event callbacks into a map of `{event: onceWrapper}`. | // Reduces the event callbacks into a map of `{event: onceWrapper}`. | |||
skipping to change at line 351 | skipping to change at line 351 | |||
var length = Math.max(0, arguments.length - 1); | var length = Math.max(0, arguments.length - 1); | |||
var args = Array(length); | var args = Array(length); | |||
for (var i = 0; i < length; i++) args[i] = arguments[i + 1]; | for (var i = 0; i < length; i++) args[i] = arguments[i + 1]; | |||
eventsApi(triggerApi, this._events, name, void 0, args); | eventsApi(triggerApi, this._events, name, void 0, args); | |||
return this; | return this; | |||
}; | }; | |||
// Handles triggering the appropriate event callbacks. | // Handles triggering the appropriate event callbacks. | |||
var triggerApi = function(objEvents, name, cb, args) { | var triggerApi = function(objEvents, name, callback, args) { | |||
if (objEvents) { | if (objEvents) { | |||
var events = objEvents[name]; | var events = objEvents[name]; | |||
var allEvents = objEvents.all; | var allEvents = objEvents.all; | |||
if (events && allEvents) allEvents = allEvents.slice(); | if (events && allEvents) allEvents = allEvents.slice(); | |||
if (events) triggerEvents(events, args); | if (events) triggerEvents(events, args); | |||
if (allEvents) triggerEvents(allEvents, [name].concat(args)); | if (allEvents) triggerEvents(allEvents, [name].concat(args)); | |||
} | } | |||
return objEvents; | return objEvents; | |||
}; | }; | |||
skipping to change at line 397 | skipping to change at line 397 | |||
// Backbone **Models** are the basic data object in the framework -- | // Backbone **Models** are the basic data object in the framework -- | |||
// frequently representing a row in a table in a database on your server. | // frequently representing a row in a table in a database on your server. | |||
// A discrete chunk of data and a bunch of useful, related methods for | // A discrete chunk of data and a bunch of useful, related methods for | |||
// performing computations and transformations on that data. | // performing computations and transformations on that data. | |||
// Create a new model with the specified attributes. A client id (`cid`) | // Create a new model with the specified attributes. A client id (`cid`) | |||
// is automatically generated and assigned for you. | // is automatically generated and assigned for you. | |||
var Model = Backbone.Model = function(attributes, options) { | var Model = Backbone.Model = function(attributes, options) { | |||
var attrs = attributes || {}; | var attrs = attributes || {}; | |||
options || (options = {}); | options || (options = {}); | |||
this.preinitialize.apply(this, arguments); | ||||
this.cid = _.uniqueId(this.cidPrefix); | this.cid = _.uniqueId(this.cidPrefix); | |||
this.attributes = {}; | this.attributes = {}; | |||
if (options.collection) this.collection = options.collection; | if (options.collection) this.collection = options.collection; | |||
if (options.parse) attrs = this.parse(attrs, options) || {}; | if (options.parse) attrs = this.parse(attrs, options) || {}; | |||
attrs = _.defaults({}, attrs, _.result(this, 'defaults')); | var defaults = _.result(this, 'defaults'); | |||
attrs = _.defaults(_.extend({}, defaults, attrs), defaults); | ||||
this.set(attrs, options); | this.set(attrs, options); | |||
this.changed = {}; | this.changed = {}; | |||
this.initialize.apply(this, arguments); | this.initialize.apply(this, arguments); | |||
}; | }; | |||
// Attach all inheritable methods to the Model prototype. | // Attach all inheritable methods to the Model prototype. | |||
_.extend(Model.prototype, Events, { | _.extend(Model.prototype, Events, { | |||
// A hash of attributes whose current and previous value differ. | // A hash of attributes whose current and previous value differ. | |||
changed: null, | changed: null, | |||
skipping to change at line 424 | skipping to change at line 426 | |||
validationError: null, | validationError: null, | |||
// The default name for the JSON `id` attribute is `"id"`. MongoDB and | // The default name for the JSON `id` attribute is `"id"`. MongoDB and | |||
// CouchDB users may want to set this to `"_id"`. | // CouchDB users may want to set this to `"_id"`. | |||
idAttribute: 'id', | idAttribute: 'id', | |||
// The prefix is used to create the client id which is used to identify mode ls locally. | // The prefix is used to create the client id which is used to identify mode ls locally. | |||
// You may want to override this if you're experiencing name clashes with mo del ids. | // You may want to override this if you're experiencing name clashes with mo del ids. | |||
cidPrefix: 'c', | cidPrefix: 'c', | |||
// preinitialize is an empty function by default. You can override it with a | ||||
function | ||||
// or object. preinitialize will run before any instantiation logic is run | ||||
in the Model. | ||||
preinitialize: function(){}, | ||||
// Initialize is an empty function by default. Override it with your own | // Initialize is an empty function by default. Override it with your own | |||
// initialization logic. | // initialization logic. | |||
initialize: function(){}, | initialize: function(){}, | |||
// Return a copy of the model's `attributes` object. | // Return a copy of the model's `attributes` object. | |||
toJSON: function(options) { | toJSON: function(options) { | |||
return _.clone(this.attributes); | return _.clone(this.attributes); | |||
}, | }, | |||
// Proxy `Backbone.sync` by default -- but override this if you need | // Proxy `Backbone.sync` by default -- but override this if you need | |||
skipping to change at line 564 | skipping to change at line 570 | |||
// Return an object containing all the attributes that have changed, or | // Return an object containing all the attributes that have changed, or | |||
// false if there are no changed attributes. Useful for determining what | // false if there are no changed attributes. Useful for determining what | |||
// parts of a view need to be updated and/or what attributes need to be | // parts of a view need to be updated and/or what attributes need to be | |||
// persisted to the server. Unset attributes will be set to undefined. | // persisted to the server. Unset attributes will be set to undefined. | |||
// You can also pass an attributes object to diff against the model, | // You can also pass an attributes object to diff against the model, | |||
// determining if there *would be* a change. | // determining if there *would be* a change. | |||
changedAttributes: function(diff) { | changedAttributes: function(diff) { | |||
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; | if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; | |||
var old = this._changing ? this._previousAttributes : this.attributes; | var old = this._changing ? this._previousAttributes : this.attributes; | |||
var changed = {}; | var changed = {}; | |||
var hasChanged; | ||||
for (var attr in diff) { | for (var attr in diff) { | |||
var val = diff[attr]; | var val = diff[attr]; | |||
if (_.isEqual(old[attr], val)) continue; | if (_.isEqual(old[attr], val)) continue; | |||
changed[attr] = val; | changed[attr] = val; | |||
hasChanged = true; | ||||
} | } | |||
return _.size(changed) ? changed : false; | return hasChanged ? changed : false; | |||
}, | }, | |||
// Get the previous value of an attribute, recorded at the time the last | // Get the previous value of an attribute, recorded at the time the last | |||
// `"change"` event was fired. | // `"change"` event was fired. | |||
previous: function(attr) { | previous: function(attr) { | |||
if (attr == null || !this._previousAttributes) return null; | if (attr == null || !this._previousAttributes) return null; | |||
return this._previousAttributes[attr]; | return this._previousAttributes[attr]; | |||
}, | }, | |||
// Get all of the attributes of the model at the time of the previous | // Get all of the attributes of the model at the time of the previous | |||
skipping to change at line 717 | skipping to change at line 725 | |||
return new this.constructor(this.attributes); | return new this.constructor(this.attributes); | |||
}, | }, | |||
// A model is new if it has never been saved to the server, and lacks an id. | // A model is new if it has never been saved to the server, and lacks an id. | |||
isNew: function() { | isNew: function() { | |||
return !this.has(this.idAttribute); | return !this.has(this.idAttribute); | |||
}, | }, | |||
// Check if the model is currently in a valid state. | // Check if the model is currently in a valid state. | |||
isValid: function(options) { | isValid: function(options) { | |||
return this._validate({}, _.defaults({validate: true}, options)); | return this._validate({}, _.extend({}, options, {validate: true})); | |||
}, | }, | |||
// Run validation against the next complete set of model attributes, | // Run validation against the next complete set of model attributes, | |||
// returning `true` if all is well. Otherwise, fire an `"invalid"` event. | // returning `true` if all is well. Otherwise, fire an `"invalid"` event. | |||
_validate: function(attrs, options) { | _validate: function(attrs, options) { | |||
if (!options.validate || !this.validate) return true; | if (!options.validate || !this.validate) return true; | |||
attrs = _.extend({}, this.attributes, attrs); | attrs = _.extend({}, this.attributes, attrs); | |||
var error = this.validationError = this.validate(attrs, options) || null; | var error = this.validationError = this.validate(attrs, options) || null; | |||
if (!error) return true; | if (!error) return true; | |||
this.trigger('invalid', this, error, _.extend(options, {validationError: e rror})); | this.trigger('invalid', this, error, _.extend(options, {validationError: e rror})); | |||
skipping to change at line 756 | skipping to change at line 764 | |||
// table, or a collection of rows that belong together for a particular reason | // table, or a collection of rows that belong together for a particular reason | |||
// -- all of the messages in this particular folder, all of the documents | // -- all of the messages in this particular folder, all of the documents | |||
// belonging to this particular author, and so on. Collections maintain | // belonging to this particular author, and so on. Collections maintain | |||
// indexes of their models, both in order, and for lookup by `id`. | // indexes of their models, both in order, and for lookup by `id`. | |||
// Create a new **Collection**, perhaps to contain a specific type of `model`. | // Create a new **Collection**, perhaps to contain a specific type of `model`. | |||
// If a `comparator` is specified, the Collection will maintain | // If a `comparator` is specified, the Collection will maintain | |||
// its models in sort order, as they're added and removed. | // its models in sort order, as they're added and removed. | |||
var Collection = Backbone.Collection = function(models, options) { | var Collection = Backbone.Collection = function(models, options) { | |||
options || (options = {}); | options || (options = {}); | |||
this.preinitialize.apply(this, arguments); | ||||
if (options.model) this.model = options.model; | if (options.model) this.model = options.model; | |||
if (options.comparator !== void 0) this.comparator = options.comparator; | if (options.comparator !== void 0) this.comparator = options.comparator; | |||
this._reset(); | this._reset(); | |||
this.initialize.apply(this, arguments); | this.initialize.apply(this, arguments); | |||
if (models) this.reset(models, _.extend({silent: true}, options)); | if (models) this.reset(models, _.extend({silent: true}, options)); | |||
}; | }; | |||
// Default options for `Collection#set`. | // Default options for `Collection#set`. | |||
var setOptions = {add: true, remove: true, merge: true}; | var setOptions = {add: true, remove: true, merge: true}; | |||
var addOptions = {add: true, remove: false}; | var addOptions = {add: true, remove: false}; | |||
// Splices `insert` into `array` at index `at`. | // Splices `insert` into `array` at index `at`. | |||
var splice = function(array, insert, at) { | var splice = function(array, insert, at) { | |||
at = Math.min(Math.max(at, 0), array.length); | at = Math.min(Math.max(at, 0), array.length); | |||
var tail = Array(array.length - at); | var tail = Array(array.length - at); | |||
var length = insert.length; | var length = insert.length; | |||
for (var i = 0; i < tail.length; i++) tail[i] = array[i + at]; | var i; | |||
for (i = 0; i < tail.length; i++) tail[i] = array[i + at]; | ||||
for (i = 0; i < length; i++) array[i + at] = insert[i]; | for (i = 0; i < length; i++) array[i + at] = insert[i]; | |||
for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i]; | for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i]; | |||
}; | }; | |||
// Define the Collection's inheritable methods. | // Define the Collection's inheritable methods. | |||
_.extend(Collection.prototype, Events, { | _.extend(Collection.prototype, Events, { | |||
// The default model for a collection is just a **Backbone.Model**. | // The default model for a collection is just a **Backbone.Model**. | |||
// This should be overridden in most cases. | // This should be overridden in most cases. | |||
model: Model, | model: Model, | |||
// preinitialize is an empty function by default. You can override it with a | ||||
function | ||||
// or object. preinitialize will run before any instantiation logic is run | ||||
in the Collection. | ||||
preinitialize: function(){}, | ||||
// Initialize is an empty function by default. Override it with your own | // Initialize is an empty function by default. Override it with your own | |||
// initialization logic. | // initialization logic. | |||
initialize: function(){}, | initialize: function(){}, | |||
// The JSON representation of a Collection is an array of the | // The JSON representation of a Collection is an array of the | |||
// models' attributes. | // models' attributes. | |||
toJSON: function(options) { | toJSON: function(options) { | |||
return this.map(function(model) { return model.toJSON(options); }); | return this.map(function(model) { return model.toJSON(options); }); | |||
}, | }, | |||
skipping to change at line 812 | skipping to change at line 826 | |||
add: function(models, options) { | add: function(models, options) { | |||
return this.set(models, _.extend({merge: false}, options, addOptions)); | return this.set(models, _.extend({merge: false}, options, addOptions)); | |||
}, | }, | |||
// Remove a model, or a list of models from the set. | // Remove a model, or a list of models from the set. | |||
remove: function(models, options) { | remove: function(models, options) { | |||
options = _.extend({}, options); | options = _.extend({}, options); | |||
var singular = !_.isArray(models); | var singular = !_.isArray(models); | |||
models = singular ? [models] : models.slice(); | models = singular ? [models] : models.slice(); | |||
var removed = this._removeModels(models, options); | var removed = this._removeModels(models, options); | |||
if (!options.silent && removed.length) this.trigger('update', this, option | if (!options.silent && removed.length) { | |||
s); | options.changes = {added: [], merged: [], removed: removed}; | |||
this.trigger('update', this, options); | ||||
} | ||||
return singular ? removed[0] : removed; | return singular ? removed[0] : removed; | |||
}, | }, | |||
// Update a collection by `set`-ing a new list of models, adding new ones, | // Update a collection by `set`-ing a new list of models, adding new ones, | |||
// removing models that are no longer present, and merging models that | // removing models that are no longer present, and merging models that | |||
// already exist in the collection, as necessary. Similar to **Model#set**, | // already exist in the collection, as necessary. Similar to **Model#set**, | |||
// the core operation for updating the data contained by the collection. | // the core operation for updating the data contained by the collection. | |||
set: function(models, options) { | set: function(models, options) { | |||
if (models == null) return; | if (models == null) return; | |||
options = _.defaults({}, options, setOptions); | options = _.extend({}, setOptions, options); | |||
if (options.parse && !this._isModel(models)) models = this.parse(models, o | if (options.parse && !this._isModel(models)) { | |||
ptions); | models = this.parse(models, options) || []; | |||
} | ||||
var singular = !_.isArray(models); | var singular = !_.isArray(models); | |||
models = singular ? (models ? [models] : []) : models.slice(); | models = singular ? [models] : models.slice(); | |||
var at = options.at; | var at = options.at; | |||
if (at != null) at = +at; | if (at != null) at = +at; | |||
if (at > this.length) at = this.length; | ||||
if (at < 0) at += this.length + 1; | if (at < 0) at += this.length + 1; | |||
var set = []; | var set = []; | |||
var toAdd = []; | var toAdd = []; | |||
var toMerge = []; | ||||
var toRemove = []; | var toRemove = []; | |||
var modelMap = {}; | var modelMap = {}; | |||
var add = options.add; | var add = options.add; | |||
var merge = options.merge; | var merge = options.merge; | |||
var remove = options.remove; | var remove = options.remove; | |||
var sort = false; | var sort = false; | |||
var sortable = this.comparator && at == null && options.sort !== false; | var sortable = this.comparator && at == null && options.sort !== false; | |||
var sortAttr = _.isString(this.comparator) ? this.comparator : null; | var sortAttr = _.isString(this.comparator) ? this.comparator : null; | |||
// Turn bare objects into model references, and prevent invalid models | // Turn bare objects into model references, and prevent invalid models | |||
// from being added. | // from being added. | |||
var model; | var model, i; | |||
for (var i = 0; i < models.length; i++) { | for (i = 0; i < models.length; i++) { | |||
model = models[i]; | model = models[i]; | |||
// If a duplicate is found, prevent it from being added and | // If a duplicate is found, prevent it from being added and | |||
// optionally merge it into the existing model. | // optionally merge it into the existing model. | |||
var existing = this.get(model); | var existing = this.get(model); | |||
if (existing) { | if (existing) { | |||
if (merge && model !== existing) { | if (merge && model !== existing) { | |||
var attrs = this._isModel(model) ? model.attributes : model; | var attrs = this._isModel(model) ? model.attributes : model; | |||
if (options.parse) attrs = existing.parse(attrs, options); | if (options.parse) attrs = existing.parse(attrs, options); | |||
existing.set(attrs, options); | existing.set(attrs, options); | |||
toMerge.push(existing); | ||||
if (sortable && !sort) sort = existing.hasChanged(sortAttr); | if (sortable && !sort) sort = existing.hasChanged(sortAttr); | |||
} | } | |||
if (!modelMap[existing.cid]) { | if (!modelMap[existing.cid]) { | |||
modelMap[existing.cid] = true; | modelMap[existing.cid] = true; | |||
set.push(existing); | set.push(existing); | |||
} | } | |||
models[i] = existing; | models[i] = existing; | |||
// If this is a new, valid model, push it to the `toAdd` list. | // If this is a new, valid model, push it to the `toAdd` list. | |||
} else if (add) { | } else if (add) { | |||
skipping to change at line 893 | skipping to change at line 915 | |||
model = this.models[i]; | model = this.models[i]; | |||
if (!modelMap[model.cid]) toRemove.push(model); | if (!modelMap[model.cid]) toRemove.push(model); | |||
} | } | |||
if (toRemove.length) this._removeModels(toRemove, options); | if (toRemove.length) this._removeModels(toRemove, options); | |||
} | } | |||
// See if sorting is needed, update `length` and splice in new models. | // See if sorting is needed, update `length` and splice in new models. | |||
var orderChanged = false; | var orderChanged = false; | |||
var replace = !sortable && add && remove; | var replace = !sortable && add && remove; | |||
if (set.length && replace) { | if (set.length && replace) { | |||
orderChanged = this.length != set.length || _.some(this.models, function | orderChanged = this.length !== set.length || _.some(this.models, functio | |||
(model, index) { | n(m, index) { | |||
return model !== set[index]; | return m !== set[index]; | |||
}); | }); | |||
this.models.length = 0; | this.models.length = 0; | |||
splice(this.models, set, 0); | splice(this.models, set, 0); | |||
this.length = this.models.length; | this.length = this.models.length; | |||
} else if (toAdd.length) { | } else if (toAdd.length) { | |||
if (sortable) sort = true; | if (sortable) sort = true; | |||
splice(this.models, toAdd, at == null ? this.length : at); | splice(this.models, toAdd, at == null ? this.length : at); | |||
this.length = this.models.length; | this.length = this.models.length; | |||
} | } | |||
// Silently sort the collection if appropriate. | // Silently sort the collection if appropriate. | |||
if (sort) this.sort({silent: true}); | if (sort) this.sort({silent: true}); | |||
// Unless silenced, it's time to fire all appropriate add/sort events. | // Unless silenced, it's time to fire all appropriate add/sort/update even ts. | |||
if (!options.silent) { | if (!options.silent) { | |||
for (i = 0; i < toAdd.length; i++) { | for (i = 0; i < toAdd.length; i++) { | |||
if (at != null) options.index = at + i; | if (at != null) options.index = at + i; | |||
model = toAdd[i]; | model = toAdd[i]; | |||
model.trigger('add', model, this, options); | model.trigger('add', model, this, options); | |||
} | } | |||
if (sort || orderChanged) this.trigger('sort', this, options); | if (sort || orderChanged) this.trigger('sort', this, options); | |||
if (toAdd.length || toRemove.length) this.trigger('update', this, option | if (toAdd.length || toRemove.length || toMerge.length) { | |||
s); | options.changes = { | |||
added: toAdd, | ||||
removed: toRemove, | ||||
merged: toMerge | ||||
}; | ||||
this.trigger('update', this, options); | ||||
} | ||||
} | } | |||
// Return the added (or merged) model (or models). | // Return the added (or merged) model (or models). | |||
return singular ? models[0] : models; | return singular ? models[0] : models; | |||
}, | }, | |||
// When you have more items than you want to add or remove individually, | // When you have more items than you want to add or remove individually, | |||
// you can reset the entire set with a new list of models, without firing | // you can reset the entire set with a new list of models, without firing | |||
// any granular `add` or `remove` events. Fires `reset` when finished. | // any granular `add` or `remove` events. Fires `reset` when finished. | |||
// Useful for bulk operations and optimizations. | // Useful for bulk operations and optimizations. | |||
skipping to change at line 966 | skipping to change at line 995 | |||
shift: function(options) { | shift: function(options) { | |||
var model = this.at(0); | var model = this.at(0); | |||
return this.remove(model, options); | return this.remove(model, options); | |||
}, | }, | |||
// Slice out a sub-array of models from the collection. | // Slice out a sub-array of models from the collection. | |||
slice: function() { | slice: function() { | |||
return slice.apply(this.models, arguments); | return slice.apply(this.models, arguments); | |||
}, | }, | |||
// Get a model from the set by id. | // Get a model from the set by id, cid, model object with id or cid | |||
// properties, or an attributes object that is transformed through modelId. | ||||
get: function(obj) { | get: function(obj) { | |||
if (obj == null) return void 0; | if (obj == null) return void 0; | |||
var id = this.modelId(this._isModel(obj) ? obj.attributes : obj); | return this._byId[obj] || | |||
return this._byId[obj] || this._byId[id] || this._byId[obj.cid]; | this._byId[this.modelId(obj.attributes || obj)] || | |||
obj.cid && this._byId[obj.cid]; | ||||
}, | ||||
// Returns `true` if the model is in the collection. | ||||
has: function(obj) { | ||||
return this.get(obj) != null; | ||||
}, | }, | |||
// Get the model at the given index. | // Get the model at the given index. | |||
at: function(index) { | at: function(index) { | |||
if (index < 0) index += this.length; | if (index < 0) index += this.length; | |||
return this.models[index]; | return this.models[index]; | |||
}, | }, | |||
// Return models with matching attributes. Useful for simple cases of | // Return models with matching attributes. Useful for simple cases of | |||
// `filter`. | // `filter`. | |||
skipping to change at line 1045 | skipping to change at line 1081 | |||
// collection immediately, unless `wait: true` is passed, in which case we | // collection immediately, unless `wait: true` is passed, in which case we | |||
// wait for the server to agree. | // wait for the server to agree. | |||
create: function(model, options) { | create: function(model, options) { | |||
options = options ? _.clone(options) : {}; | options = options ? _.clone(options) : {}; | |||
var wait = options.wait; | var wait = options.wait; | |||
model = this._prepareModel(model, options); | model = this._prepareModel(model, options); | |||
if (!model) return false; | if (!model) return false; | |||
if (!wait) this.add(model, options); | if (!wait) this.add(model, options); | |||
var collection = this; | var collection = this; | |||
var success = options.success; | var success = options.success; | |||
options.success = function(model, resp, callbackOpts) { | options.success = function(m, resp, callbackOpts) { | |||
if (wait) collection.add(model, callbackOpts); | if (wait) collection.add(m, callbackOpts); | |||
if (success) success.call(callbackOpts.context, model, resp, callbackOpt | if (success) success.call(callbackOpts.context, m, resp, callbackOpts); | |||
s); | ||||
}; | }; | |||
model.save(null, options); | model.save(null, options); | |||
return model; | return model; | |||
}, | }, | |||
// **parse** converts a response into a list of models to be added to the | // **parse** converts a response into a list of models to be added to the | |||
// collection. The default implementation is just to pass it through. | // collection. The default implementation is just to pass it through. | |||
parse: function(resp, options) { | parse: function(resp, options) { | |||
return resp; | return resp; | |||
}, | }, | |||
skipping to change at line 1198 | skipping to change at line 1234 | |||
// DOM. This might be a single item, an entire list, a sidebar or panel, or | // DOM. This might be a single item, an entire list, a sidebar or panel, or | |||
// even the surrounding frame which wraps your whole app. Defining a chunk of | // even the surrounding frame which wraps your whole app. Defining a chunk of | |||
// UI as a **View** allows you to define your DOM events declaratively, withou t | // UI as a **View** allows you to define your DOM events declaratively, withou t | |||
// having to worry about render order ... and makes it easy for the view to | // having to worry about render order ... and makes it easy for the view to | |||
// react to specific changes in the state of your models. | // react to specific changes in the state of your models. | |||
// Creating a Backbone.View creates its initial element outside of the DOM, | // Creating a Backbone.View creates its initial element outside of the DOM, | |||
// if an existing element is not provided... | // if an existing element is not provided... | |||
var View = Backbone.View = function(options) { | var View = Backbone.View = function(options) { | |||
this.cid = _.uniqueId('view'); | this.cid = _.uniqueId('view'); | |||
this.preinitialize.apply(this, arguments); | ||||
_.extend(this, _.pick(options, viewOptions)); | _.extend(this, _.pick(options, viewOptions)); | |||
this._ensureElement(); | this._ensureElement(); | |||
this.initialize.apply(this, arguments); | this.initialize.apply(this, arguments); | |||
}; | }; | |||
// Cached regex to split keys for `delegate`. | // Cached regex to split keys for `delegate`. | |||
var delegateEventSplitter = /^(\S+)\s*(.*)$/; | var delegateEventSplitter = /^(\S+)\s*(.*)$/; | |||
// List of view options to be set as properties. | // List of view options to be set as properties. | |||
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className ', 'tagName', 'events']; | var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className ', 'tagName', 'events']; | |||
skipping to change at line 1221 | skipping to change at line 1258 | |||
// The default `tagName` of a View's element is `"div"`. | // The default `tagName` of a View's element is `"div"`. | |||
tagName: 'div', | tagName: 'div', | |||
// jQuery delegate for element lookup, scoped to DOM elements within the | // jQuery delegate for element lookup, scoped to DOM elements within the | |||
// current view. This should be preferred to global lookups where possible. | // current view. This should be preferred to global lookups where possible. | |||
$: function(selector) { | $: function(selector) { | |||
return this.$el.find(selector); | return this.$el.find(selector); | |||
}, | }, | |||
// preinitialize is an empty function by default. You can override it with a | ||||
function | ||||
// or object. preinitialize will run before any instantiation logic is run | ||||
in the View | ||||
preinitialize: function(){}, | ||||
// Initialize is an empty function by default. Override it with your own | // Initialize is an empty function by default. Override it with your own | |||
// initialization logic. | // initialization logic. | |||
initialize: function(){}, | initialize: function(){}, | |||
// **render** is the core function that your view should override, in order | // **render** is the core function that your view should override, in order | |||
// to populate its element (`this.el`), with the appropriate HTML. The | // to populate its element (`this.el`), with the appropriate HTML. The | |||
// convention is for **render** to always return `this`. | // convention is for **render** to always return `this`. | |||
render: function() { | render: function() { | |||
return this; | return this; | |||
}, | }, | |||
skipping to change at line 1446 | skipping to change at line 1487 | |||
return Backbone.$.ajax.apply(Backbone.$, arguments); | return Backbone.$.ajax.apply(Backbone.$, arguments); | |||
}; | }; | |||
// Backbone.Router | // Backbone.Router | |||
// --------------- | // --------------- | |||
// Routers map faux-URLs to actions, and fire events when routes are | // Routers map faux-URLs to actions, and fire events when routes are | |||
// matched. Creating a new one sets its `routes` hash, if not set statically. | // matched. Creating a new one sets its `routes` hash, if not set statically. | |||
var Router = Backbone.Router = function(options) { | var Router = Backbone.Router = function(options) { | |||
options || (options = {}); | options || (options = {}); | |||
this.preinitialize.apply(this, arguments); | ||||
if (options.routes) this.routes = options.routes; | if (options.routes) this.routes = options.routes; | |||
this._bindRoutes(); | this._bindRoutes(); | |||
this.initialize.apply(this, arguments); | this.initialize.apply(this, arguments); | |||
}; | }; | |||
// Cached regular expressions for matching named param parts and splatted | // Cached regular expressions for matching named param parts and splatted | |||
// parts of route strings. | // parts of route strings. | |||
var optionalParam = /\((.*?)\)/g; | var optionalParam = /\((.*?)\)/g; | |||
var namedParam = /(\(\?)?:\w+/g; | var namedParam = /(\(\?)?:\w+/g; | |||
var splatParam = /\*\w+/g; | var splatParam = /\*\w+/g; | |||
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; | var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; | |||
// Set up all inheritable **Backbone.Router** properties and methods. | // Set up all inheritable **Backbone.Router** properties and methods. | |||
_.extend(Router.prototype, Events, { | _.extend(Router.prototype, Events, { | |||
// preinitialize is an empty function by default. You can override it with a | ||||
function | ||||
// or object. preinitialize will run before any instantiation logic is run | ||||
in the Router. | ||||
preinitialize: function(){}, | ||||
// Initialize is an empty function by default. Override it with your own | // Initialize is an empty function by default. Override it with your own | |||
// initialization logic. | // initialization logic. | |||
initialize: function(){}, | initialize: function(){}, | |||
// Manually bind a single named route to a callback. For example: | // Manually bind a single named route to a callback. For example: | |||
// | // | |||
// this.route('search/:query/p:num', 'search', function(query, num) { | // this.route('search/:query/p:num', 'search', function(query, num) { | |||
// ... | // ... | |||
// }); | // }); | |||
// | // | |||
skipping to change at line 1587 | skipping to change at line 1633 | |||
// Are we at the app root? | // Are we at the app root? | |||
atRoot: function() { | atRoot: function() { | |||
var path = this.location.pathname.replace(/[^\/]$/, '$&/'); | var path = this.location.pathname.replace(/[^\/]$/, '$&/'); | |||
return path === this.root && !this.getSearch(); | return path === this.root && !this.getSearch(); | |||
}, | }, | |||
// Does the pathname match the root? | // Does the pathname match the root? | |||
matchRoot: function() { | matchRoot: function() { | |||
var path = this.decodeFragment(this.location.pathname); | var path = this.decodeFragment(this.location.pathname); | |||
var root = path.slice(0, this.root.length - 1) + '/'; | var rootPath = path.slice(0, this.root.length - 1) + '/'; | |||
return root === this.root; | return rootPath === this.root; | |||
}, | }, | |||
// Unicode characters in `location.pathname` are percent encoded so they're | // Unicode characters in `location.pathname` are percent encoded so they're | |||
// decoded for comparison. `%25` should not be decoded since it may be part | // decoded for comparison. `%25` should not be decoded since it may be part | |||
// of an encoded parameter. | // of an encoded parameter. | |||
decodeFragment: function(fragment) { | decodeFragment: function(fragment) { | |||
return decodeURI(fragment.replace(/%25/g, '%2525')); | return decodeURI(fragment.replace(/%25/g, '%2525')); | |||
}, | }, | |||
// In IE6, the hash fragment and search params are incorrect if the | // In IE6, the hash fragment and search params are incorrect if the | |||
skipping to change at line 1660 | skipping to change at line 1706 | |||
// Normalize root to always include a leading and trailing slash. | // Normalize root to always include a leading and trailing slash. | |||
this.root = ('/' + this.root + '/').replace(rootStripper, '/'); | this.root = ('/' + this.root + '/').replace(rootStripper, '/'); | |||
// Transition from hashChange to pushState or vice versa if both are | // Transition from hashChange to pushState or vice versa if both are | |||
// requested. | // requested. | |||
if (this._wantsHashChange && this._wantsPushState) { | if (this._wantsHashChange && this._wantsPushState) { | |||
// If we've started off with a route from a `pushState`-enabled | // If we've started off with a route from a `pushState`-enabled | |||
// browser, but we're currently in a browser that doesn't support it... | // browser, but we're currently in a browser that doesn't support it... | |||
if (!this._hasPushState && !this.atRoot()) { | if (!this._hasPushState && !this.atRoot()) { | |||
var root = this.root.slice(0, -1) || '/'; | var rootPath = this.root.slice(0, -1) || '/'; | |||
this.location.replace(root + '#' + this.getPath()); | this.location.replace(rootPath + '#' + this.getPath()); | |||
// Return immediately as browser will do redirect to new url | // Return immediately as browser will do redirect to new url | |||
return true; | return true; | |||
// Or if we've started out with a hash-based route, but we're currently | // Or if we've started out with a hash-based route, but we're currently | |||
// in a browser where it could be `pushState`-based instead... | // in a browser where it could be `pushState`-based instead... | |||
} else if (this._hasPushState && this.atRoot()) { | } else if (this._hasPushState && this.atRoot()) { | |||
this.navigate(this.getHash(), {replace: true}); | this.navigate(this.getHash(), {replace: true}); | |||
} | } | |||
} | } | |||
skipping to change at line 1785 | skipping to change at line 1831 | |||
// route callback be fired (not usually desirable), or `replace: true`, if | // route callback be fired (not usually desirable), or `replace: true`, if | |||
// you wish to modify the current URL without adding an entry to the history . | // you wish to modify the current URL without adding an entry to the history . | |||
navigate: function(fragment, options) { | navigate: function(fragment, options) { | |||
if (!History.started) return false; | if (!History.started) return false; | |||
if (!options || options === true) options = {trigger: !!options}; | if (!options || options === true) options = {trigger: !!options}; | |||
// Normalize the fragment. | // Normalize the fragment. | |||
fragment = this.getFragment(fragment || ''); | fragment = this.getFragment(fragment || ''); | |||
// Don't include a trailing slash on the root. | // Don't include a trailing slash on the root. | |||
var root = this.root; | var rootPath = this.root; | |||
if (fragment === '' || fragment.charAt(0) === '?') { | if (fragment === '' || fragment.charAt(0) === '?') { | |||
root = root.slice(0, -1) || '/'; | rootPath = rootPath.slice(0, -1) || '/'; | |||
} | } | |||
var url = root + fragment; | var url = rootPath + fragment; | |||
// Strip the fragment of the query and hash for matching. | ||||
fragment = fragment.replace(pathStripper, ''); | ||||
// Strip the hash and decode for matching. | // Decode for matching. | |||
fragment = this.decodeFragment(fragment.replace(pathStripper, '')); | var decodedFragment = this.decodeFragment(fragment); | |||
if (this.fragment === fragment) return; | if (this.fragment === decodedFragment) return; | |||
this.fragment = fragment; | this.fragment = decodedFragment; | |||
// If pushState is available, we use it to set the fragment as a real URL. | // If pushState is available, we use it to set the fragment as a real URL. | |||
if (this._usePushState) { | if (this._usePushState) { | |||
this.history[options.replace ? 'replaceState' : 'pushState']({}, documen t.title, url); | this.history[options.replace ? 'replaceState' : 'pushState']({}, documen t.title, url); | |||
// If hash changes haven't been explicitly disabled, update the hash | // If hash changes haven't been explicitly disabled, update the hash | |||
// fragment to store history. | // fragment to store history. | |||
} else if (this._wantsHashChange) { | } else if (this._wantsHashChange) { | |||
this._updateHash(this.location, fragment, options.replace); | this._updateHash(this.location, fragment, options.replace); | |||
if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) { | if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) { | |||
skipping to change at line 1896 | skipping to change at line 1945 | |||
// Wrap an optional error callback with a fallback error event. | // Wrap an optional error callback with a fallback error event. | |||
var wrapError = function(model, options) { | var wrapError = function(model, options) { | |||
var error = options.error; | var error = options.error; | |||
options.error = function(resp) { | options.error = function(resp) { | |||
if (error) error.call(options.context, model, resp, options); | if (error) error.call(options.context, model, resp, options); | |||
model.trigger('error', model, resp, options); | model.trigger('error', model, resp, options); | |||
}; | }; | |||
}; | }; | |||
return Backbone; | return Backbone; | |||
}); | }); | |||
End of changes. 44 change blocks. | ||||
47 lines changed or deleted | 99 lines changed or added |