diff --git a/vendor/backbone/backbone.js b/vendor/backbone/backbone.js index 3512d42fb..f7783c2c1 100644 --- a/vendor/backbone/backbone.js +++ b/vendor/backbone/backbone.js @@ -1,6 +1,7 @@ -// Backbone.js 1.0.0 +// Backbone.js 1.1.0 -// (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc. +// (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc. +// (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org @@ -34,7 +35,7 @@ } // Current version of the library. Keep in sync with `package.json`. - Backbone.VERSION = '1.0.0'; + Backbone.VERSION = '1.1.0'; // Require Underscore, if we're on the server, and it's not already present. var _ = root._; @@ -52,7 +53,7 @@ }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option - // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and + // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; @@ -111,7 +112,6 @@ this._events = {}; return this; } - names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; @@ -151,14 +151,15 @@ // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function(obj, name, callback) { - var listeners = this._listeners; - if (!listeners) return this; - var deleteListener = !name && !callback; - if (typeof name === 'object') callback = this; - if (obj) (listeners = {})[obj._listenerId] = obj; - for (var id in listeners) { - listeners[id].off(name, callback, this); - if (deleteListener) delete this._listeners[id]; + var listeningTo = this._listeningTo; + if (!listeningTo) return this; + var remove = !name && !callback; + if (!callback && typeof name === 'object') callback = this; + if (obj) (listeningTo = {})[obj._listenId] = obj; + for (var id in listeningTo) { + obj = listeningTo[id]; + obj.off(name, callback, this); + if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } @@ -215,10 +216,10 @@ // listening to. _.each(listenMethods, function(implementation, method) { Events[method] = function(obj, name, callback) { - var listeners = this._listeners || (this._listeners = {}); - var id = obj._listenerId || (obj._listenerId = _.uniqueId('l')); - listeners[id] = obj; - if (typeof name === 'object') callback = this; + var listeningTo = this._listeningTo || (this._listeningTo = {}); + var id = obj._listenId || (obj._listenId = _.uniqueId('l')); + listeningTo[id] = obj; + if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; @@ -243,24 +244,18 @@ // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { - var defaults; var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; - _.extend(this, _.pick(options, modelOptions)); + if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; - if (defaults = _.result(this, 'defaults')) { - attrs = _.defaults({}, attrs, defaults); - } + attrs = _.defaults({}, attrs, _.result(this, 'defaults')); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; - // A list of options to be attached directly to the model, if provided. - var modelOptions = ['url', 'urlRoot', 'collection']; - // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { @@ -456,13 +451,16 @@ (attrs = {})[key] = val; } - // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`. - if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false; - options = _.extend({validate: true}, options); - // Do not persist invalid models. - if (!this._validate(attrs, options)) return false; + // If we're not waiting and attributes exist, save acts as + // `set(attr).save(null, opts)` with validation. Otherwise, check if + // the model will be valid when the attributes, if any, are set. + if (attrs && !options.wait) { + if (!this.set(attrs, options)) return false; + } else { + if (!this._validate(attrs, options)) return false; + } // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { @@ -563,7 +561,7 @@ attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; - this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error})); + this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } @@ -596,7 +594,6 @@ // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); - if (options.url) this.url = options.url; if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); @@ -606,7 +603,7 @@ // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; - var addOptions = {add: true, merge: false, remove: false}; + var addOptions = {add: true, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { @@ -632,16 +629,17 @@ // Add a model, or list of models to the set. add: function(models, options) { - return this.set(models, _.defaults(options || {}, addOptions)); + return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { - models = _.isArray(models) ? models.slice() : [models]; + var singular = !_.isArray(models); + models = singular ? [models] : _.clone(models); options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { - model = this.get(models[i]); + model = models[i] = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; @@ -654,7 +652,7 @@ } this._removeReference(model); } - return this; + return singular ? models[0] : models; }, // Update a collection by `set`-ing a new list of models, adding new ones, @@ -662,31 +660,45 @@ // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { - options = _.defaults(options || {}, setOptions); + options = _.defaults({}, options, setOptions); if (options.parse) models = this.parse(models, options); - if (!_.isArray(models)) models = models ? [models] : []; - var i, l, model, attrs, existing, sort; + var singular = !_.isArray(models); + models = singular ? (models ? [models] : []) : _.clone(models); + var i, l, id, model, attrs, existing, sort; var at = options.at; + var targetModel = this.model; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; + var add = options.add, merge = options.merge, remove = options.remove; + var order = !sortable && add && remove ? [] : false; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { - if (!(model = this._prepareModel(models[i], options))) continue; + attrs = models[i]; + if (attrs instanceof Model) { + id = model = attrs; + } else { + id = attrs[targetModel.prototype.idAttribute]; + } // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. - if (existing = this.get(model)) { - if (options.remove) modelMap[existing.cid] = true; - if (options.merge) { - existing.set(model.attributes, options); + if (existing = this.get(id)) { + if (remove) modelMap[existing.cid] = true; + if (merge) { + attrs = attrs === model ? model.attributes : attrs; + if (options.parse) attrs = existing.parse(attrs, options); + existing.set(attrs, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } + models[i] = existing; - // This is a new model, push it to the `toAdd` list. - } else if (options.add) { + // If this is a new, valid model, push it to the `toAdd` list. + } else if (add) { + model = models[i] = this._prepareModel(attrs, options); + if (!model) continue; toAdd.push(model); // Listen to added models' events, and index models for lookup by @@ -695,10 +707,11 @@ this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; } + if (order) order.push(existing || model); } // Remove nonexistent models if appropriate. - if (options.remove) { + if (remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } @@ -706,29 +719,35 @@ } // See if sorting is needed, update `length` and splice in new models. - if (toAdd.length) { + if (toAdd.length || (order && order.length)) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { - splice.apply(this.models, [at, 0].concat(toAdd)); + for (i = 0, l = toAdd.length; i < l; i++) { + this.models.splice(at + i, 0, toAdd[i]); + } } else { - push.apply(this.models, toAdd); + if (order) this.models.length = 0; + var orderedModels = order || toAdd; + for (i = 0, l = orderedModels.length; i < l; i++) { + this.models.push(orderedModels[i]); + } } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); - if (options.silent) return this; - - // Trigger `add` events. - for (i = 0, l = toAdd.length; i < l; i++) { - (model = toAdd[i]).trigger('add', model, this, options); + // Unless silenced, it's time to fire all appropriate add/sort events. + if (!options.silent) { + for (i = 0, l = toAdd.length; i < l; i++) { + (model = toAdd[i]).trigger('add', model, this, options); + } + if (sort || (order && order.length)) this.trigger('sort', this, options); } - - // Trigger `sort` if the collection was sorted. - if (sort) this.trigger('sort', this, options); - return this; + + // Return the added (or merged) model (or models). + return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, @@ -742,16 +761,14 @@ } options.previousModels = this.models; this._reset(); - this.add(models, _.extend({silent: true}, options)); + models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); - return this; + return models; }, // Add a model to the end of the collection. push: function(model, options) { - model = this._prepareModel(model, options); - this.add(model, _.extend({at: this.length}, options)); - return model; + return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. @@ -763,9 +780,7 @@ // Add a model to the beginning of the collection. unshift: function(model, options) { - model = this._prepareModel(model, options); - this.add(model, _.extend({at: 0}, options)); - return model; + return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. @@ -776,14 +791,14 @@ }, // Slice out a sub-array of models from the collection. - slice: function(begin, end) { - return this.models.slice(begin, end); + slice: function() { + return slice.apply(this.models, arguments); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; - return this._byId[obj.id != null ? obj.id : obj.cid || obj]; + return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj]; }, // Get the model at the given index. @@ -827,16 +842,6 @@ return this; }, - // Figure out the smallest index at which a model should be inserted so as - // to maintain order. - sortedIndex: function(model, value, context) { - value || (value = this.comparator); - var iterator = _.isFunction(value) ? value : function(model) { - return model.get(value); - }; - return _.sortedIndex(this.models, model, iterator, context); - }, - // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); @@ -869,7 +874,7 @@ if (!options.wait) this.add(model, options); var collection = this; var success = options.success; - options.success = function(resp) { + options.success = function(model, resp, options) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; @@ -903,14 +908,12 @@ if (!attrs.collection) attrs.collection = this; return attrs; } - options || (options = {}); + options = options ? _.clone(options) : {}; options.collection = this; var model = new this.model(attrs, options); - if (!model._validate(attrs, options)) { - this.trigger('invalid', this, attrs, options); - return false; - } - return model; + if (!model.validationError) return model; + this.trigger('invalid', this, model.validationError, options); + return false; }, // Internal method to sever a model's ties to a collection. @@ -942,8 +945,8 @@ 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', - 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', - 'isEmpty', 'chain']; + 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', + 'lastIndexOf', 'isEmpty', 'chain']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { @@ -982,7 +985,8 @@ // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); - this._configure(options || {}); + options || (options = {}); + _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); @@ -1001,7 +1005,7 @@ tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the - // current view. This should be prefered to global lookups where possible. + // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, @@ -1041,7 +1045,7 @@ // // { // 'mousedown .title': 'edit', - // 'click .button': 'save' + // 'click .button': 'save', // 'click .open': function(e) { ... } // } // @@ -1079,16 +1083,6 @@ return this; }, - // Performs the initial configuration of a View with a set of options. - // Keys with special meaning *(e.g. model, collection, id, className)* are - // attached directly to the view. See `viewOptions` for an exhaustive - // list. - _configure: function(options) { - if (this.options) options = _.extend({}, _.result(this, 'options'), options); - _.extend(this, _.pick(options, viewOptions)); - this.options = options; - }, - // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create @@ -1174,8 +1168,7 @@ // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. - if (params.type === 'PATCH' && window.ActiveXObject && - !(window.external && window.external.msActiveXFilteringEnabled)) { + if (params.type === 'PATCH' && noXhrPatch) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; @@ -1187,6 +1180,8 @@ return xhr; }; + var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); + // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', @@ -1275,7 +1270,7 @@ _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') - .replace(namedParam, function(match, optional){ + .replace(namedParam, function(match, optional) { return optional ? match : '([^\/]+)'; }) .replace(splatParam, '(.*?)'); @@ -1325,6 +1320,9 @@ // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; + // Cached regex for stripping urls of hash and query. + var pathStripper = /[?#].*$/; + // Has the history handling already been started? History.started = false; @@ -1349,7 +1347,7 @@ if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = this.location.pathname; var root = this.root.replace(trailingSlash, ''); - if (!fragment.indexOf(root)) fragment = fragment.substr(root.length); + if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); } else { fragment = this.getHash(); } @@ -1365,7 +1363,7 @@ // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? - this.options = _.extend({}, {root: '/'}, this.options, options); + this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; @@ -1398,19 +1396,25 @@ var loc = this.location; var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root; - // 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... - if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) { - this.fragment = this.getFragment(null, true); - this.location.replace(this.root + this.location.search + '#' + this.fragment); - // Return immediately as browser will do redirect to new url - return true; + // Transition from hashChange to pushState or vice versa if both are + // requested. + if (this._wantsHashChange && this._wantsPushState) { + + // 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... + if (!this._hasPushState && !atRoot) { + this.fragment = this.getFragment(null, true); + this.location.replace(this.root + this.location.search + '#' + this.fragment); + // Return immediately as browser will do redirect to new url + return true; + + // 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... + } else if (this._hasPushState && atRoot && loc.hash) { + this.fragment = this.getHash().replace(routeStripper, ''); + this.history.replaceState({}, document.title, this.root + this.fragment + loc.search); + } - // 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... - } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) { - this.fragment = this.getHash().replace(routeStripper, ''); - this.history.replaceState({}, document.title, this.root + this.fragment + loc.search); } if (!this.options.silent) return this.loadUrl(); @@ -1439,21 +1443,20 @@ } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); - this.loadUrl() || this.loadUrl(this.getHash()); + this.loadUrl(); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. - loadUrl: function(fragmentOverride) { - var fragment = this.fragment = this.getFragment(fragmentOverride); - var matched = _.any(this.handlers, function(handler) { + loadUrl: function(fragment) { + fragment = this.fragment = this.getFragment(fragment); + return _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); - return matched; }, // Save a fragment into the hash history, or replace the URL state if the @@ -1465,11 +1468,18 @@ // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; - if (!options || options === true) options = {trigger: options}; - fragment = this.getFragment(fragment || ''); + if (!options || options === true) options = {trigger: !!options}; + + var url = this.root + (fragment = this.getFragment(fragment || '')); + + // Strip the fragment of the query and hash for matching. + fragment = fragment.replace(pathStripper, ''); + if (this.fragment === fragment) return; this.fragment = fragment; - var url = this.root + fragment; + + // Don't include a trailing slash on the root. + if (fragment === '' && url !== '/') url = url.slice(0, -1); // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { @@ -1492,7 +1502,7 @@ } else { return this.location.assign(url); } - if (options.trigger) this.loadUrl(fragment); + if (options.trigger) return this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding @@ -1560,7 +1570,7 @@ }; // Wrap an optional error callback with a fallback error event. - var wrapError = function (model, options) { + var wrapError = function(model, options) { var error = options.error; options.error = function(resp) { if (error) error(model, resp, options); diff --git a/vendor/backbone/test/collection.js b/vendor/backbone/test/collection.js index d068b3961..748d7bba0 100644 --- a/vendor/backbone/test/collection.js +++ b/vendor/backbone/test/collection.js @@ -1,12 +1,10 @@ -$(document).ready(function() { +(function() { var a, b, c, d, e, col, otherCol; - module("Backbone.Collection", _.extend(new Environment, { + module("Backbone.Collection", { setup: function() { - Environment.prototype.setup.apply(this, arguments); - a = new Backbone.Model({id: 3, label: 'a'}); b = new Backbone.Model({id: 2, label: 'b'}); c = new Backbone.Model({id: 1, label: 'c'}); @@ -16,7 +14,7 @@ $(document).ready(function() { otherCol = new Backbone.Collection(); } - })); + }); test("new and sort", 9, function() { var counter = 0; @@ -87,7 +85,7 @@ $(document).ready(function() { equal(col2.get(model.clone()), col2.first()); }); - test("update index when id changes", 3, function() { + test("update index when id changes", 4, function() { var col = new Backbone.Collection(); col.add([ {id : 0, name : 'one'}, @@ -95,9 +93,10 @@ $(document).ready(function() { ]); var one = col.get(0); equal(one.get('name'), 'one'); - one.set({id : 101}); + col.on('change:name', function (model) { ok(this.get(model)); }); + one.set({name: 'dalmatians', id : 101}); equal(col.get(0), null); - equal(col.get(101).get('name'), 'one'); + equal(col.get(101).get('name'), 'dalmatians'); }); test("at", 1, function() { @@ -226,13 +225,13 @@ $(document).ready(function() { }); test("add with parse and merge", function() { - var Model = Backbone.Model.extend({ - parse: function (data) { - return data.model; - } - }); var collection = new Backbone.Collection(); - collection.model = Model; + collection.parse = function(attrs) { + return _.map(attrs, function(model) { + if (model.model) return model.model; + return model; + }); + }; collection.add({id: 1}); collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true}); equal(collection.first().get('name'), 'Alf'); @@ -288,6 +287,39 @@ $(document).ready(function() { equal(otherRemoved, null); }); + test("add and remove return values", 13, function() { + var Even = Backbone.Model.extend({ + validate: function(attrs) { + if (attrs.id % 2 !== 0) return "odd"; + } + }); + var col = new Backbone.Collection; + col.model = Even; + + var list = col.add([{id: 2}, {id: 4}], {validate: true}); + equal(list.length, 2); + ok(list[0] instanceof Backbone.Model); + equal(list[1], col.last()); + equal(list[1].get('id'), 4); + + list = col.add([{id: 3}, {id: 6}], {validate: true}); + equal(col.length, 3); + equal(list[0], false); + equal(list[1].get('id'), 6); + + var result = col.add({id: 6}); + equal(result.cid, list[1].cid); + + result = col.remove({id: 6}); + equal(col.length, 2); + equal(result.id, 6); + + list = col.remove([{id: 2}, {id: 8}]); + equal(col.length, 1); + equal(list[0].get('id'), 2); + equal(list[1], null); + }); + test("shift and pop", 2, function() { var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]); equal(col.shift().get('a'), 'a'); @@ -438,7 +470,7 @@ $(document).ready(function() { equal(model.collection, collection); }); - test("create with validate:true enforces validation", 2, function() { + test("create with validate:true enforces validation", 3, function() { var ValidatingModel = Backbone.Model.extend({ validate: function(attrs) { return "fail"; @@ -448,7 +480,8 @@ $(document).ready(function() { model: ValidatingModel }); var col = new ValidatingCollection(); - col.on('invalid', function (collection, attrs, options) { + col.on('invalid', function (collection, error, options) { + equal(error, "fail"); equal(options.validationError, 'fail'); }); equal(col.create({"foo":"bar"}, {validate:true}), false); @@ -502,7 +535,7 @@ $(document).ready(function() { equal(coll.findWhere({a: 4}), void 0); }); - test("Underscore methods", 13, function() { + test("Underscore methods", 14, function() { equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d'); equal(col.any(function(model){ return model.id === 100; }), false); equal(col.any(function(model){ return model.id === 0; }), true); @@ -520,18 +553,7 @@ $(document).ready(function() { .map(function(o){ return o.id * 2; }) .value(), [4, 0]); - }); - - test("sortedIndex", function () { - var model = new Backbone.Model({key: 2}); - var collection = new (Backbone.Collection.extend({ - comparator: 'key' - }))([model, {key: 1}]); - equal(collection.sortedIndex(model), 1); - equal(collection.sortedIndex(model, 'key'), 1); - equal(collection.sortedIndex(model, function (model) { - return model.get('key'); - }), 1); + deepEqual(col.difference([c, d]), [a, b]); }); test("reset", 12, function() { @@ -920,6 +942,20 @@ $(document).ready(function() { strictEqual(c.length, 0); }); + test("set with many models does not overflow the stack", function() { + var n = 150000; + var collection = new Backbone.Collection(); + var models = []; + for (var i = 0; i < n; i++) { + models.push({id: i}); + } + collection.set(models); + equal(collection.length, n); + collection.reset(); + collection.set(models, {at: 0}); + equal(collection.length, n); + }); + test("set with only cids", 3, function() { var m1 = new Backbone.Model; var m2 = new Backbone.Model; @@ -963,17 +999,33 @@ $(document).ready(function() { equal(col.first().get('key'), 'other'); col.set({id: 1, other: 'value'}); - equal(col.first().get('key'), 'value'); + equal(col.first().get('key'), 'other'); equal(col.length, 1); }); - test("`set` and model level `parse`", function() { + test('merge without mutation', function () { var Model = Backbone.Model.extend({ - parse: function (res) { return res.model; } + initialize: function (attrs, options) { + if (attrs.child) { + this.set('child', new Model(attrs.child, options), options); + } + } }); + var Collection = Backbone.Collection.extend({model: Model}); + var data = [{id: 1, child: {id: 2}}]; + var collection = new Collection(data); + equal(collection.first().id, 1); + collection.set(data); + equal(collection.first().id, 1); + collection.set([{id: 2, child: {id: 2}}].concat(data)); + deepEqual(collection.pluck('id'), [2, 1]); + }); + + test("`set` and model level `parse`", function() { + var Model = Backbone.Model.extend({}); var Collection = Backbone.Collection.extend({ model: Model, - parse: function (res) { return res.models; } + parse: function (res) { return _.pluck(res.models, 'model'); } }); var model = new Model({id: 1}); var collection = new Collection(model); @@ -996,6 +1048,25 @@ $(document).ready(function() { collection.set({}, {parse: true}); }); + test('`set` matches input order in the absence of a comparator', function () { + var one = new Backbone.Model({id: 1}); + var two = new Backbone.Model({id: 2}); + var three = new Backbone.Model({id: 3}); + var collection = new Backbone.Collection([one, two, three]); + collection.set([{id: 3}, {id: 2}, {id: 1}]); + deepEqual(collection.models, [three, two, one]); + collection.set([{id: 1}, {id: 2}]); + deepEqual(collection.models, [one, two]); + collection.set([two, three, one]); + deepEqual(collection.models, [two, three, one]); + collection.set([{id: 1}, {id: 2}], {remove: false}); + deepEqual(collection.models, [two, three, one]); + collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false}); + deepEqual(collection.models, [one, two, three]); + collection.set([three, two, one, {id: 4}], {add: false}); + deepEqual(collection.models, [one, two, three]); + }); + test("#1894 - Push should not trigger a sort", 0, function() { var Collection = Backbone.Collection.extend({ comparator: 'id', @@ -1006,6 +1077,13 @@ $(document).ready(function() { new Collection().push({id: 1}); }); + test("#2428 - push duplicate models, return the correct one", 1, function() { + var col = new Backbone.Collection; + var model1 = col.push({id: 101}); + var model2 = col.push({id: 101}) + ok(model2.cid == model1.cid); + }); + test("`set` with non-normal id", function() { var Collection = Backbone.Collection.extend({ model: Backbone.Model.extend({idAttribute: '_id'}) @@ -1081,20 +1159,119 @@ $(document).ready(function() { collection.add(collection.models, {merge: true}); // don't sort }); - test("Attach options to collection.", 3, function() { - var url = '/somewhere'; - var model = new Backbone.Model; - var comparator = function(){}; + test("Attach options to collection.", 2, function() { + var model = new Backbone.Model; + var comparator = function(){}; - var collection = new Backbone.Collection([], { - url: url, - model: model, - comparator: comparator - }); + var collection = new Backbone.Collection([], { + model: model, + comparator: comparator + }); - strictEqual(collection.url, url); - ok(collection.model === model); - ok(collection.comparator === comparator); + ok(collection.model === model); + ok(collection.comparator === comparator); }); -}); + test("`add` overrides `set` flags", function () { + var collection = new Backbone.Collection(); + collection.once('add', function (model, collection, options) { + collection.add({id: 2}, options); + }); + collection.set({id: 1}); + equal(collection.length, 2); + }); + + test("#2606 - Collection#create, success arguments", 1, function() { + var collection = new Backbone.Collection; + collection.url = 'test'; + collection.create({}, { + success: function(model, resp, options) { + strictEqual(resp, 'response'); + } + }); + this.ajaxSettings.success('response'); + }); + + test("#2612 - nested `parse` works with `Collection#set`", function() { + + var Job = Backbone.Model.extend({ + constructor: function() { + this.items = new Items(); + Backbone.Model.apply(this, arguments); + }, + parse: function(attrs) { + this.items.set(attrs.items, {parse: true}); + return _.omit(attrs, 'items'); + } + }); + + var Item = Backbone.Model.extend({ + constructor: function() { + this.subItems = new Backbone.Collection(); + Backbone.Model.apply(this, arguments); + }, + parse: function(attrs) { + this.subItems.set(attrs.subItems, {parse: true}); + return _.omit(attrs, 'subItems'); + } + }); + + var Items = Backbone.Collection.extend({ + model: Item + }); + + var data = { + name: 'JobName', + id: 1, + items: [{ + id: 1, + name: 'Sub1', + subItems: [ + {id: 1, subName: 'One'}, + {id: 2, subName: 'Two'} + ] + }, { + id: 2, + name: 'Sub2', + subItems: [ + {id: 3, subName: 'Three'}, + {id: 4, subName: 'Four'} + ] + }] + }; + + var newData = { + name: 'NewJobName', + id: 1, + items: [{ + id: 1, + name: 'NewSub1', + subItems: [ + {id: 1,subName: 'NewOne'}, + {id: 2,subName: 'NewTwo'} + ] + }, { + id: 2, + name: 'NewSub2', + subItems: [ + {id: 3,subName: 'NewThree'}, + {id: 4,subName: 'NewFour'} + ] + }] + }; + + var job = new Job(data, {parse: true}); + equal(job.get('name'), 'JobName'); + equal(job.items.at(0).get('name'), 'Sub1'); + equal(job.items.length, 2); + equal(job.items.get(1).subItems.get(1).get('subName'), 'One'); + equal(job.items.get(2).subItems.get(3).get('subName'), 'Three'); + job.set(job.parse(newData, {parse: true})); + equal(job.get('name'), 'NewJobName'); + equal(job.items.at(0).get('name'), 'NewSub1'); + equal(job.items.length, 2); + equal(job.items.get(1).subItems.get(1).get('subName'), 'NewOne'); + equal(job.items.get(2).subItems.get(3).get('subName'), 'NewThree'); + }); + +})(); diff --git a/vendor/backbone/test/environment.js b/vendor/backbone/test/environment.js index 54aa2c407..996884bbe 100644 --- a/vendor/backbone/test/environment.js +++ b/vendor/backbone/test/environment.js @@ -1,45 +1,35 @@ (function() { - var Environment = this.Environment = function(){}; + var sync = Backbone.sync; + var ajax = Backbone.ajax; + var emulateHTTP = Backbone.emulateHTTP; + var emulateJSON = Backbone.emulateJSON; - _.extend(Environment.prototype, { + QUnit.testStart(function() { + var env = this.config.current.testEnvironment; - ajax: Backbone.ajax, + // Capture ajax settings for comparison. + Backbone.ajax = function(settings) { + env.ajaxSettings = settings; + }; - sync: Backbone.sync, - - emulateHTTP: Backbone.emulateHTTP, - - emulateJSON: Backbone.emulateJSON, - - setup: function() { - var env = this; - - // Capture ajax settings for comparison. - Backbone.ajax = function(settings) { - env.ajaxSettings = settings; + // Capture the arguments to Backbone.sync for comparison. + Backbone.sync = function(method, model, options) { + env.syncArgs = { + method: method, + model: model, + options: options }; - - // Capture the arguments to Backbone.sync for comparison. - Backbone.sync = function(method, model, options) { - env.syncArgs = { - method: method, - model: model, - options: options - }; - env.sync.apply(this, arguments); - }; - }, - - teardown: function() { - this.syncArgs = null; - this.ajaxSettings = null; - Backbone.sync = this.sync; - Backbone.ajax = this.ajax; - Backbone.emulateHTTP = this.emulateHTTP; - Backbone.emulateJSON = this.emulateJSON; - } + sync.apply(this, arguments); + }; }); + QUnit.testDone(function() { + Backbone.sync = sync; + Backbone.ajax = ajax; + Backbone.emulateHTTP = emulateHTTP; + Backbone.emulateJSON = emulateJSON; + }); + })(); diff --git a/vendor/backbone/test/events.js b/vendor/backbone/test/events.js index 1aa746cce..9f6878e43 100644 --- a/vendor/backbone/test/events.js +++ b/vendor/backbone/test/events.js @@ -1,4 +1,4 @@ -$(document).ready(function() { +(function() { module("Backbone.Events"); @@ -152,6 +152,31 @@ $(document).ready(function() { e.trigger("foo"); }); + test("stopListening cleans up references", 4, function() { + var a = _.extend({}, Backbone.Events); + var b = _.extend({}, Backbone.Events); + var fn = function() {}; + a.listenTo(b, 'all', fn).stopListening(); + equal(_.size(a._listeningTo), 0); + a.listenTo(b, 'all', fn).stopListening(b); + equal(_.size(a._listeningTo), 0); + a.listenTo(b, 'all', fn).stopListening(null, 'all'); + equal(_.size(a._listeningTo), 0); + a.listenTo(b, 'all', fn).stopListening(null, null, fn); + equal(_.size(a._listeningTo), 0); + }); + + test("listenTo and stopListening cleaning up references", 2, function() { + var a = _.extend({}, Backbone.Events); + var b = _.extend({}, Backbone.Events); + a.listenTo(b, 'all', function(){ ok(true); }); + b.trigger('anything'); + a.listenTo(b, 'other', function(){ ok(false); }); + a.stopListening(b, 'other'); + a.stopListening(b, 'all'); + equal(_.keys(a._listeningTo).length, 0); + }); + test("listenTo with empty callback doesn't throw an error", 1, function(){ var e = _.extend({}, Backbone.Events); e.listenTo(e, "foo", null); @@ -449,4 +474,4 @@ $(document).ready(function() { equal(obj, obj.stopListening()); }); -}); +})(); diff --git a/vendor/backbone/test/model.js b/vendor/backbone/test/model.js index 3b196c48e..ec1ba54af 100644 --- a/vendor/backbone/test/model.js +++ b/vendor/backbone/test/model.js @@ -1,4 +1,4 @@ -$(document).ready(function() { +(function() { var proxy = Backbone.Model.extend(); var klass = Backbone.Collection.extend({ @@ -6,10 +6,9 @@ $(document).ready(function() { }); var doc, collection; - module("Backbone.Model", _.extend(new Environment, { + module("Backbone.Model", { setup: function() { - Environment.prototype.setup.apply(this, arguments); doc = new proxy({ id : '1-the-tempest', title : "The Tempest", @@ -20,7 +19,7 @@ $(document).ready(function() { collection.add(doc); } - })); + }); test("initialize", 3, function() { var Model = Backbone.Model.extend({ @@ -111,13 +110,6 @@ $(document).ready(function() { equal(model.url(), '/nested/1/collection/2'); }); - test('url and urlRoot are directly attached if passed in the options', 2, function () { - var model = new Backbone.Model({a: 1}, {url: '/test'}); - var model2 = new Backbone.Model({a: 2}, {urlRoot: '/test2'}); - equal(model.url, '/test'); - equal(model2.urlRoot, '/test2'); - }); - test("underscore methods", 5, function() { var model = new Backbone.Model({ 'foo': 'a', 'bar': 'b', 'baz': 'c' }); var model2 = model.clone(); @@ -712,6 +704,22 @@ $(document).ready(function() { ok(this.syncArgs.model === model); }); + test("save without `wait` doesn't set invalid attributes", function () { + var model = new Backbone.Model(); + model.validate = function () { return 1; } + model.save({a: 1}); + equal(model.get('a'), void 0); + }); + + test("save doesn't validate twice", function () { + var model = new Backbone.Model(); + var times = 0; + model.sync = function () {}; + model.validate = function () { ++times; } + model.save({}); + equal(times, 1); + }); + test("`hasChanged` for falsey keys", 2, function() { var model = new Backbone.Model(); model.set({x: true}, {silent: true}); @@ -1099,4 +1107,4 @@ $(document).ready(function() { model.set({a: true}); }); -}); +})(); diff --git a/vendor/backbone/test/noconflict.js b/vendor/backbone/test/noconflict.js index a0e55cac2..ac4324d02 100644 --- a/vendor/backbone/test/noconflict.js +++ b/vendor/backbone/test/noconflict.js @@ -1,4 +1,4 @@ -$(document).ready(function() { +(function() { module("Backbone.noConflict"); @@ -9,4 +9,4 @@ $(document).ready(function() { equal(window.Backbone, noconflictBackbone, 'Backbone is still pointing to the original Backbone'); }); -}); +})(); diff --git a/vendor/backbone/test/router.js b/vendor/backbone/test/router.js index e6e1b3d6e..296546e4d 100644 --- a/vendor/backbone/test/router.js +++ b/vendor/backbone/test/router.js @@ -1,4 +1,4 @@ -$(document).ready(function() { +(function() { var router = null; var location = null; @@ -75,6 +75,8 @@ $(document).ready(function() { "counter": "counter", "search/:query": "search", "search/:query/p:page": "search", + "charñ": "charUTF", + "char%C3%B1": "charEscaped", "contacts": "contacts", "contacts/new": "newContact", "contacts/:id": "loadContact", @@ -103,11 +105,19 @@ $(document).ready(function() { this.count++; }, - search : function(query, page) { + search: function(query, page) { this.query = query; this.page = page; }, + charUTF: function() { + this.charType = 'UTF'; + }, + + charEscaped: function() { + this.charType = 'escaped'; + }, + contacts: function(){ this.contact = 'index'; }, @@ -204,6 +214,10 @@ $(document).ready(function() { equal(router.page, '20'); }); + test("reports matched route via nagivate", 1, function() { + ok(Backbone.history.navigate('search/manhattan/p20', true)); + }); + test("route precedence via navigate", 6, function(){ // check both 0.9.x and backwards-compatibility options _.each([ { trigger: true }, true ], function( options ){ @@ -349,6 +363,13 @@ $(document).ready(function() { equal(lastRoute, 'search'); }); + test("#2666 - Hashes with UTF8 in them.", 2, function() { + Backbone.history.navigate('charñ', {trigger: true}); + equal(router.charType, 'UTF'); + Backbone.history.navigate('char%C3%B1', {trigger: true}); + equal(router.charType, 'escaped'); + }); + test("#1185 - Use pathname when hashChange is not wanted.", 1, function() { Backbone.history.stop(); location.replace('http://example.com/path/name#hash'); @@ -609,4 +630,100 @@ $(document).ready(function() { deepEqual({home: "root", index: "index.html", show: "show", search: "search"}, router.routes); }); -}); + test("#2538 - hashChange to pushState only if both requested.", 0, function() { + Backbone.history.stop(); + location.replace('http://example.com/root?a=b#x/y'); + Backbone.history = _.extend(new Backbone.History, { + location: location, + history: { + pushState: function(){}, + replaceState: function(){ ok(false); } + } + }); + Backbone.history.start({ + root: 'root', + pushState: true, + hashChange: false + }); + }); + + test('No hash fallback.', 0, function() { + Backbone.history.stop(); + Backbone.history = _.extend(new Backbone.History, { + location: location, + history: { + pushState: function(){}, + replaceState: function(){} + } + }); + + var Router = Backbone.Router.extend({ + routes: { + hash: function() { ok(false); } + } + }); + var router = new Router; + + location.replace('http://example.com/'); + Backbone.history.start({ + pushState: true, + hashChange: false + }); + location.replace('http://example.com/nomatch#hash'); + Backbone.history.checkUrl(); + }); + + test('#2656 - No trailing slash on root.', 1, function() { + Backbone.history.stop(); + Backbone.history = _.extend(new Backbone.History, { + location: location, + history: { + pushState: function(state, title, url){ + strictEqual(url, '/root'); + } + } + }); + location.replace('http://example.com/root/path'); + Backbone.history.start({pushState: true, root: 'root'}); + Backbone.history.navigate(''); + }); + + test('#2656 - No trailing slash on root.', 1, function() { + Backbone.history.stop(); + Backbone.history = _.extend(new Backbone.History, { + location: location, + history: { + pushState: function(state, title, url) { + strictEqual(url, '/'); + } + } + }); + location.replace('http://example.com/path'); + Backbone.history.start({pushState: true}); + Backbone.history.navigate(''); + }); + + test('#2765 - Fragment matching sans query/hash.', 2, function() { + Backbone.history.stop(); + Backbone.history = _.extend(new Backbone.History, { + location: location, + history: { + pushState: function(state, title, url) { + strictEqual(url, '/path?query#hash'); + } + } + }); + + var Router = Backbone.Router.extend({ + routes: { + path: function() { ok(true); } + } + }); + var router = new Router; + + location.replace('http://example.com/'); + Backbone.history.start({pushState: true}); + Backbone.history.navigate('path?query#hash', true); + }); + +})(); diff --git a/vendor/backbone/test/sync.js b/vendor/backbone/test/sync.js index 8fddb47fa..d54a7963b 100644 --- a/vendor/backbone/test/sync.js +++ b/vendor/backbone/test/sync.js @@ -1,4 +1,4 @@ -$(document).ready(function() { +(function() { var Library = Backbone.Collection.extend({ url : function() { return '/library'; } @@ -11,20 +11,18 @@ $(document).ready(function() { length : 123 }; - module("Backbone.sync", _.extend(new Environment, { + module("Backbone.sync", { setup : function() { - Environment.prototype.setup.apply(this, arguments); library = new Library; library.create(attrs, {wait: false}); }, teardown: function() { - Environment.prototype.teardown.apply(this, arguments); Backbone.emulateHTTP = false; } - })); + }); test("read", 4, function() { library.fetch(); @@ -209,4 +207,4 @@ $(document).ready(function() { strictEqual(this.ajaxSettings.beforeSend(xhr), false); }); -}); +})(); diff --git a/vendor/backbone/test/view.js b/vendor/backbone/test/view.js index 58a87718d..65eee25db 100644 --- a/vendor/backbone/test/view.js +++ b/vendor/backbone/test/view.js @@ -1,4 +1,4 @@ -$(document).ready(function() { +(function() { var view; @@ -14,13 +14,10 @@ $(document).ready(function() { }); - test("constructor", 6, function() { + test("constructor", 3, function() { equal(view.el.id, 'test-view'); equal(view.el.className, 'test-view'); equal(view.el.other, void 0); - equal(view.options.id, 'test-view'); - equal(view.options.className, 'test-view'); - equal(view.options.other, 'non-special-option'); }); test("jQuery", 1, function() { @@ -156,30 +153,6 @@ $(document).ready(function() { strictEqual(new View().el.id, 'id'); }); - test("with options function", 3, function() { - var View1 = Backbone.View.extend({ - options: function() { - return { - title: 'title1', - acceptText: 'confirm' - }; - } - }); - - var View2 = View1.extend({ - options: function() { - return _.extend(View1.prototype.options.call(this), { - title: 'title2', - fixed: true - }); - } - }); - - strictEqual(new View2().options.title, 'title2'); - strictEqual(new View2().options.acceptText, 'confirm'); - strictEqual(new View2().options.fixed, true); - }); - test("with attributes", 2, function() { var View = Backbone.View.extend({ attributes: { @@ -319,7 +292,7 @@ $(document).ready(function() { view.collection.trigger('x'); }); - test("Provide function for el.", 1, function() { + test("Provide function for el.", 2, function() { var View = Backbone.View.extend({ el: function() { return "
"; @@ -327,7 +300,8 @@ $(document).ready(function() { }); var view = new View; - ok(view.$el.is('p:has(a)')); + ok(view.$el.is('p')); + ok(view.$el.has('a')); }); test("events passed in options", 2, function() { @@ -354,4 +328,4 @@ $(document).ready(function() { equal(counter, 4); }); -}); +})();