-(function(factory) {diff --git a/.eslintrc b/.eslintrc
new file mode 100644
index 00000000..f1b5b3c4
--- /dev/null
+++ b/.eslintrc
@@ -0,0 +1,90 @@
+{
+ "env": {
+ "browser": true,
+ "node": true,
+ "amd": true
+ },
+ "globals": {
+ "attachEvent": false,
+ "detachEvent": false
+ },
+ "rules": {
+ "array-bracket-spacing": 2,
+ "block-scoped-var": 2,
+ "brace-style": [1, "1tbs", {"allowSingleLine": true}],
+ "camelcase": 2,
+ "comma-dangle": [2, "never"],
+ "comma-spacing": 2,
+ "computed-property-spacing": [2, "never"],
+ "dot-notation": [2, { "allowKeywords": false }],
+ "eol-last": 2,
+ "eqeqeq": [2, "smart"],
+ "indent": [2, 2, {"SwitchCase": 1, "VariableDeclarator": 2}],
+ "key-spacing": 1,
+ "keyword-spacing": [2, { "after": true }],
+ "linebreak-style": 2,
+ "max-depth": [1, 4],
+ "max-params": [1, 5],
+ "new-cap": [2, {"newIsCapExceptions": ["model"]}],
+ "no-alert": 2,
+ "no-caller": 2,
+ "no-catch-shadow": 2,
+ "no-console": 2,
+ "no-debugger": 2,
+ "no-delete-var": 2,
+ "no-div-regex": 1,
+ "no-dupe-args": 2,
+ "no-dupe-keys": 2,
+ "no-duplicate-case": 2,
+ "no-else-return": 1,
+ "no-empty-character-class": 2,
+ "no-eval": 2,
+ "no-ex-assign": 2,
+ "no-extend-native": 2,
+ "no-extra-boolean-cast": 2,
+ "no-extra-parens": 1,
+ "no-extra-semi": 2,
+ "no-fallthrough": 2,
+ "no-floating-decimal": 2,
+ "no-func-assign": 2,
+ "no-implied-eval": 2,
+ "no-inner-declarations": 2,
+ "no-irregular-whitespace": 2,
+ "no-label-var": 2,
+ "no-labels": 2,
+ "no-lone-blocks": 2,
+ "no-lonely-if": 2,
+ "no-multi-str": 2,
+ "no-native-reassign": 2,
+ "no-negated-in-lhs": 1,
+ "no-new-object": 2,
+ "no-new-wrappers": 2,
+ "no-obj-calls": 2,
+ "no-octal": 2,
+ "no-octal-escape": 2,
+ "no-proto": 2,
+ "no-redeclare": 2,
+ "no-shadow": 2,
+ "no-spaced-func": 2,
+ "no-throw-literal": 2,
+ "no-trailing-spaces": 2,
+ "no-undef": 2,
+ "no-undef-init": 2,
+ "no-undefined": 2,
+ "no-unneeded-ternary": 2,
+ "no-unreachable": 2,
+ "no-unused-expressions": [2, {"allowTernary": true, "allowShortCircuit": true}],
+ "no-with": 2,
+ "object-curly-spacing": [2, "never"],
+ "quote-props": [1, "consistent-as-needed"],
+ "quotes": [2, "single", "avoid-escape"],
+ "radix": 2,
+ "semi": 2,
+ "space-before-function-paren": [2, {"anonymous": "never", "named": "never"}],
+ "space-infix-ops": 2,
+ "space-unary-ops": [2, { "words": true, "nonwords": false }],
+ "use-isnan": 2,
+ "valid-typeof": 2,
+ "wrap-iife": [2, "inside"]
+ }
+}
diff --git a/.travis.yml b/.travis.yml
index 0da8ccf8..aa0cd87a 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -10,14 +10,12 @@ before_script:
- sh -e /etc/init.d/xvfb start
script:
- npm test
- # Karma sauce is limited to running about 5-7 browsers (or it will timeout) at a time so we just run vendor by vendor here
- - karma start karma.conf-sauce.js --browsers FIREFOX_V4,FIREFOX_V11,FIREFOX_V21,FIREFOX_V30,FIREFOX_V35,CHROME_V26,CHROME_V31,CHROME_V39,CHROME_V40,ANDROID_V4.0,ANDROID_V4.3
- - karma start karma.conf-sauce.js --browsers IE_V7,IE_V8,IE_V9,IE_V10,IE_V11
- - karma start karma.conf-sauce.js --browsers SAFARI_V5,SAFARI_V6,SAFARI_V7,SAFARI_V8.0,OPERA_V11,OPERA_V12
+ - karma start karma.conf-sauce.js
notifications:
email: false
sudo: false
env:
global:
+ - NPM_CONFIG_PROGRESS="false"
- secure: G9oDQUXytNHni0wasGDXO3lQE/xuP9gd6VZ20kuh5FzVlqfY5L7JfYWki435nZ1z2yPD1QVAZi+1BCmCwnkTLVO9gB7cmDJDt1VzeHdCSOqCXGDAbOcq67/OO4FUa77sCQSDnqOOGVbiUPldaDl8G6uylk72Ll8b0pPwUWdRCM8=
- secure: dniSzTSxXzaSGYjW3+LiNesx/BtTWo6RHuMKm19MwNo/YJYJJ/1YSEH/9vCmlVzc00CqvJ5Khwu9XPzcDV4gkuNQFN1+QcgGI2heVUqac/jqlGF39VEH8Xc+H40MsRLkwgSIkadIPWj4wBbbzqyC9M+J/KjUPOhBXGtp+FARu0I=
diff --git a/LICENSE b/LICENSE
index 184d1b99..51d7adcb 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2010-2015 Jeremy Ashkenas, DocumentCloud
+Copyright (c) 2010-2017 Jeremy Ashkenas, DocumentCloud
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
diff --git a/README.md b/README.md
index 2f807762..276b7fc3 100644
--- a/README.md
+++ b/README.md
@@ -16,9 +16,14 @@ Backbone supplies structure to JavaScript-heavy applications by providing models
For Docs, License, Tests, pre-packed downloads, and everything else, really, see:
http://backbonejs.org
-To suggest a feature, report a bug, or general discussion:
+To suggest a feature or report a bug:
https://github.com/jashkenas/backbone/issues
+For questions on working with Backbone or general discussions:
+https://groups.google.com/forum/#!forum/backbonejs,
+http://stackoverflow.com/questions/tagged/backbone.js, or
+https://gitter.im/jashkenas/backbone
+
Backbone is an open-sourced component of DocumentCloud:
https://github.com/documentcloud
diff --git a/backbone-min.js b/backbone-min.js
index d2e95b43..435a72c9 100644
--- a/backbone-min.js
+++ b/backbone-min.js
@@ -1,2 +1,2 @@
-(function(t){var e=typeof self=="object"&&self.self==self&&self||typeof global=="object"&&global.global==global&&global;if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,s){e.Backbone=t(e,s,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore"),r;try{r=require("jquery")}catch(s){}t(e,exports,i,r)}else{e.Backbone=t(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}})(function(t,e,i,r){var s=t.Backbone;var n=[];var a=n.slice;e.VERSION="1.2.0";e.$=r;e.noConflict=function(){t.Backbone=s;return this};e.emulateHTTP=false;e.emulateJSON=false;var o=e.Events={};var h=/\s+/;var u=function(t,e,r,s,n){var a=0,o;if(r&&typeof r==="object"){for(o=i.keys(r);aBackbone.js 1.2.0
+
@@ -40,7 +40,7 @@
- Backbone.js 1.3.3
@@ -115,7 +115,7 @@ others that may still expect a global Backbone.(c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+
@@ -64,8 +64,8 @@ We use (c) 2010-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
Backbone may be freely distributed under the MIT license.
For all details and documentation:
http://backbonejs.org
@@ -48,7 +48,7 @@ http://backbonejs.org
-(function(factory) {self instead of window for WebWorker
- var root = (typeof self == 'object' && self.self == self && self) ||
- (typeof global == 'object' && global.global == global && global);
var root = (typeof self == 'object' && self.self === self && self) ||
+ (typeof global == 'object' && global.global === global && global);
self instead of window for WebWorker
if (typeof define === 'function' && define.amd) {
- define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
} else if (typeof exports !== 'undefined') {
var _ = require('underscore'), $;
- try { $ = require('jquery'); } catch(e) {}
+ try { $ = require('jquery'); } catch (e) {}
factory(root, exports, _, $);noConflict is used.
- Create local references to array methods we’ll want to use later.
+Create a local reference to a common array method we’ll want to use later.
- var array = [];
- var slice = array.slice; var slice = Array.prototype.slice;noConflict is used.
- Backbone.VERSION = '1.2.0'; Backbone.VERSION = '1.3.3'; Backbone.noConflict = function() {
+ Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
@@ -288,10 +287,41 @@ form param named model.
- Backbone.Events
+ Proxy Backbone class methods to Underscore functions, wrapping the model’s
+attributes object or collection’s models array behind the scenes.
+collection.filter(function(model) { return model.get(‘age’) > 10 });
+collection.each(this.addView);
+Function#apply can be slow so we use the method’s arg count, if we know it.
var addMethod = function(length, method, attribute) {
+ switch (length) {
+ case 1: return function() {
+ return _[method](this[attribute]);
+ };
+ case 2: return function(value) {
+ return _[method](this[attribute], value);
+ };
+ case 3: return function(iteratee, context) {
+ return _[method](this[attribute], cb(iteratee, this), context);
+ };
+ case 4: return function(iteratee, defaultVal, context) {
+ return _[method](this[attribute], cb(iteratee, this), defaultVal, context);
+ };
+ default: return function() {
+ var args = slice.call(arguments);
+ args.unshift(this[attribute]);
+ return _[method].apply(_, args);
+ };
+ }
+ };
+ var addUnderscoreMethods = function(Class, methods, attribute) {
+ _.each(methods, function(length, method) {
+ if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
+ });
+ };model.
-
+ Support collection.sortBy('attr') and collection.findWhere({id: 1}).
var cb = function(iteratee, instance) {
+ if (_.isFunction(iteratee)) return iteratee;
+ if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
+ if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
+ return iteratee;
+ };
+ var modelMatcher = function(attrs) {
+ var matcher = _.matches(attrs);
+ return function(model) {
+ return matcher(model.attributes);
+ };
+ };model.
- A module that can be mixed in to any object in order to provide it with
-custom events. You may bind with on or remove with off callback
-functions to an event; trigger-ing an event fires all callbacks in
-succession.
var object = {};
-_.extend(object, Backbone.Events);
-object.on('expand', function(){ alert('expanded'); });
-object.trigger('expand');
-
+ var Events = Backbone.Events = {};Regular expression used to split event strings.
- + - var eventSplitter = /\s+/;Iterates over the standard event, callback (as well as the fancy multiple
-space-separated events "change blur", callback and jQuery-style event
-maps {event: callback}), reducing them by manipulating memo.
-Passes a normalized single event name and callback, as well as any
-optional opts.
A module that can be mixed in to any object in order to provide it with
+a custom event channel. You may bind a callback to an event with on or
+remove with off; trigger-ing an event fires all callbacks in
+succession.
var object = {};
+_.extend(object, Backbone.Events);
+object.on('expand', function(){ alert('expanded'); });
+object.trigger('expand');
+
- var eventsApi = function(iteratee, memo, name, callback, opts) {
- var i = 0, names;
- if (name && typeof name === 'object') { var Events = Backbone.Events = {};opts.
- Handle event maps.
+Regular expression used to split event strings.
- for (names = _.keys(name); i < names.length ; i++) {
- memo = iteratee(memo, names[i], name[names[i]], opts);
- }
- } else if (name && eventSplitter.test(name)) { var eventSplitter = /\s+/;opts.
- Handle space separated event names.
+Iterates over the standard event, callback (as well as the fancy multiple
+space-separated events "change blur", callback and jQuery-style event
+maps {event: callback}).
for (names = name.split(eventSplitter); i < names.length; i++) {
- memo = iteratee(memo, names[i], callback, opts);
- }
- } else {
- memo = iteratee(memo, name, callback, opts);
- }
- return memo;
- }; var eventsApi = function(iteratee, events, name, callback, opts) {
+ var i = 0, names;
+ if (name && typeof name === 'object') {opts.
- Bind an event to a callback function. Passing "all" will bind
-the callback to all events fired.
Handle event maps.
- Events.on = function(name, callback, context) {
- return internalOn(this, name, callback, context);
- }; if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
+ for (names = _.keys(name); i < names.length ; i++) {
+ events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
+ }
+ } else if (name && eventSplitter.test(name)) {An internal use on function, used to guard the listening argument from
-the public API.
Handle space-separated event names by delegating them individually.
- var internalOn = function(obj, name, callback, context, listening) {
+ for (names = name.split(eventSplitter); i < names.length; i++) {
+ events = iteratee(events, names[i], callback, opts);
+ }
+ } else {
+
+
+
+
+ Finally, standard events.
+ + events = iteratee(events, name, callback, opts);
+ }
+ return events;
+ };Bind an event to a callback function. Passing "all" will bind
+the callback to all events fired.
Events.on = function(name, callback, context) {
+ return internalOn(this, name, callback, context);
+ };Guard the listening argument from the public API.
var internalOn = function(obj, name, callback, context, listening) {
obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
- context: context,
- ctx: obj,
- listening: listening
+ context: context,
+ ctx: obj,
+ listening: listening
});
if (listening) {
@@ -452,18 +533,19 @@ the public API.
- Inversion-of-control versions of on. Tell this object to listen to
-an event in another object… keeping track of what it’s listening to.
Events.listenTo = function(obj, name, callback) {
+ Events.listenTo = function(obj, name, callback) {
if (!obj) return this;
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
var listeningTo = this._listeningTo || (this._listeningTo = {});
@@ -472,11 +554,11 @@ an event in another object… keeping track of what it’s listening to.
-
+
This object is not listening to any other events on obj yet.
Setup the necessary references to track the listening callbacks.
@@ -491,11 +573,11 @@ Setup the necessary references to track the listening callbacks.
-
+
Bind callbacks on obj, and keep track of them on listening.
@@ -508,96 +590,25 @@ Setup the necessary references to track the listening callbacks.
-
-
-
-
- ¶
-
- The reducing API that adds a callback to the events object.
-
-
-
- var onApi = function(events, name, callback, options) {
- if (callback) {
- var handlers = events[name] || (events[name] = []);
- var context = options.context, ctx = options.ctx, listening = options.listening;
- if (listening) listening.count++;
-
- handlers.push({ callback: callback, context: context, ctx: context || ctx, listening: listening });
- }
- return events;
- };
-
-
-
-
-
-
-
-
- ¶
-
- Remove one or many callbacks. If context is null, removes all
-callbacks with that function. If callback is null, removes all
-callbacks for the event. If name is null, removes all bound
-callbacks for all events.
-
-
-
- Events.off = function(name, callback, context) {
- if (!this._events) return this;
- this._events = eventsApi(offApi, this._events, name, callback, {
- context: context,
- listeners: this._listeners
- });
- return this;
- };
-
-
-
-
-
-
-
-
- ¶
-
- Tell this object to stop listening to either specific events … or
-to every object it’s currently listening to.
-
-
-
- Events.stopListening = function(obj, name, callback) {
- var listeningTo = this._listeningTo;
- if (!listeningTo) return this;
-
- var ids = obj ? [obj._listenId] : _.keys(listeningTo);
-
- for (var i = 0; i < ids.length; i++) {
- var listening = listeningTo[ids[i]];
-
-
-
-
- If listening doesn’t exist, this object is not currently
-listening to obj. Break out early.
+ The reducing API that adds a callback to the events object.
- if (!listening) break;
+ var onApi = function(events, name, callback, options) {
+ if (callback) {
+ var handlers = events[name] || (events[name] = []);
+ var context = options.context, ctx = options.ctx, listening = options.listening;
+ if (listening) listening.count++;
- listening.obj.off(name, callback, this);
+ handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
}
- if (_.isEmpty(listeningTo)) this._listeningTo = void 0;
-
- return this;
+ return events;
};
@@ -609,11 +620,21 @@ listening to obj. Break out early.
- The reducing API that removes a callback from the events object.
+ Remove one or many callbacks. If context is null, removes all
+callbacks with that function. If callback is null, removes all
+callbacks for the event. If name is null, removes all bound
+callbacks for all events.
- var offApi = function(events, name, callback, options) {
+ Events.off = function(name, callback, context) {
+ if (!this._events) return this;
+ this._events = eventsApi(offApi, this._events, name, callback, {
+ context: context,
+ listeners: this._listeners
+ });
+ return this;
+ };
@@ -624,14 +645,19 @@ listening to obj. Break out early.
- No events to consider.
+ Tell this object to stop listening to either specific events … or
+to every object it’s currently listening to.
- if (!events) return;
+ Events.stopListening = function(obj, name, callback) {
+ var listeningTo = this._listeningTo;
+ if (!listeningTo) return this;
- var i = 0, length, listening;
- var context = options.context, listeners = options.listeners;
+ var ids = obj ? [obj._listenId] : _.keys(listeningTo);
+
+ for (var i = 0; i < ids.length; i++) {
+ var listening = listeningTo[ids[i]];
@@ -642,6 +668,47 @@ listening to obj. Break out early.
+ If listening doesn’t exist, this object is not currently
+listening to obj. Break out early.
+
+
+
+ if (!listening) break;
+
+ listening.obj.off(name, callback, this);
+ }
+
+ return this;
+ };
+
+
+
+
+
+
+
+
+ ¶
+
+ The reducing API that removes a callback from the events object.
+
+
+
+ var offApi = function(events, name, callback, options) {
+ if (!events) return;
+
+ var i = 0, listening;
+ var context = options.context, listeners = options.listeners;
+
+
+
+
+
+
+
+
+ ¶
+
Delete all events listeners and “drop” events.
@@ -664,11 +731,11 @@ listening to obj. Break out early.
-
+
Bail out if there are no events stored.
@@ -679,11 +746,11 @@ listening to obj. Break out early.
-
+
Replace events if there are any remaining. Otherwise, clean up.
@@ -710,11 +777,11 @@ listening to obj. Break out early.
-
+
-
-
-
-
-
-
-
-
- ¶
-
- Bind an event to only be triggered a single time. After the first time
-the callback is invoked, it will be removed. When multiple events are
-passed in using the space-separated syntax, the event will fire once for every
-event you passed in, not once for a combination of all events
-
-
-
- Events.once = function(name, callback, context) {
-
-
-
-
-
-
-
-
- ¶
-
- Map the event into a {event: once} object.
-
-
-
- var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this));
- return this.on(events, void 0, context);
+ return events;
};
@@ -773,11 +805,14 @@ event you passed in, not once for a combination of all events
- Inversion-of-control versions of once.
+ 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
+are passed in using the space-separated syntax, the handler will fire
+once for each event, not once for a combination of all events.
- Events.listenToOnce = function(obj, name, callback) {
+ Events.once = function(name, callback, context) {
@@ -792,8 +827,9 @@ event you passed in, not once for a combination of all events
- var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj));
- return this.listenTo(obj, events);
+ var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this));
+ if (typeof name === 'string' && context == null) callback = void 0;
+ return this.on(events, callback, context);
};
@@ -805,14 +841,46 @@ event you passed in, not once for a combination of all events
- Reduces the event callbacks into a map of {event: onceWrapper}.
-offer unbinds the onceWrapper after it as been called.
+ Inversion-of-control versions of once.
- var onceMap = function(map, name, callback, offer) {
+ Events.listenToOnce = function(obj, name, callback) {
+
+
+
+
+
+
+
+
+ ¶
+
+ Map the event into a {event: once} object.
+
+
+
+ var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj));
+ return this.listenTo(obj, events);
+ };
+
+
+
+
+
+
+
+
+ ¶
+
+ Reduces the event callbacks into a map of {event: onceWrapper}.
+offer unbinds the onceWrapper after it has been called.
+
+
+
+ var onceMap = function(map, name, callback, offer) {
if (callback) {
- var once = map[name] = _.once(function() {
+ var once = map[name] = _.once(function() {
offer(name, once);
callback.apply(this, arguments);
});
@@ -824,11 +892,11 @@ event you passed in, not once for a combination of all events
-
+
Trigger one or many events, firing all bound callbacks. Callbacks are
passed the same arguments as trigger is, apart from the event name
@@ -837,7 +905,7 @@ receive the true name of the event as the first argument).
- Events.trigger = function(name) {
+ Events.trigger = function(name) {
if (!this._events) return this;
var length = Math.max(0, arguments.length - 1);
@@ -851,17 +919,17 @@ receive the true name of the event as the first argument).
-
+
- var triggerApi = function(objEvents, name, cb, args) {
+ var triggerApi = function(objEvents, name, callback, args) {
if (objEvents) {
var events = objEvents[name];
var allEvents = objEvents.all;
@@ -875,11 +943,11 @@ receive the true name of the event as the first argument).
-
+
A difficult-to-believe, but optimized internal dispatch function for
triggering events. Tries to keep the usual cases speedy (most internal
@@ -887,8 +955,8 @@ Backbone events have 3 arguments).
- var triggerEvents = function(events, args) {
- var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
+ var triggerEvents = function(events, args) {
+ var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
@@ -901,52 +969,11 @@ Backbone events have 3 arguments).
-
+
- ¶
-
- Proxy Underscore methods to a Backbone class’ prototype using a
-particular attribute as the data argument
-
-
-
- var addMethod = function(length, method, attribute) {
- switch (length) {
- case 1: return function() {
- return _[method](this[attribute]);
- };
- case 2: return function(value) {
- return _[method](this[attribute], value);
- };
- case 3: return function(iteratee, context) {
- return _[method](this[attribute], iteratee, context);
- };
- case 4: return function(iteratee, defaultVal, context) {
- return _[method](this[attribute], iteratee, defaultVal, context);
- };
- default: return function() {
- var args = slice.call(arguments);
- args.unshift(this[attribute]);
- return _[method].apply(_, args);
- };
- }
- };
- var addUnderscoreMethods = function(Class, methods, attribute) {
- _.each(methods, function(length, method) {
- if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
- });
- };
-
-
-
-
-
-
-
-
Aliases for backwards compatibility.
@@ -958,11 +985,11 @@ particular attribute as the data argument
-
+
Allow the Backbone object to serve as a global event bus, for folks who
want global “pubsub” in a convenient place.
@@ -974,26 +1001,14 @@ want global “pubsub” in a convenient place.
-
-
-
-
- ¶
-
- Backbone.Model
-
-
-
-
-
-
-
+ Backbone.Model
+
@@ -1005,11 +1020,7 @@ want global “pubsub” in a convenient place.
- Backbone Models are the basic data object in the framework —
-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
-performing computations and transformations on that data.
-
+
@@ -1021,24 +1032,13 @@ performing computations and transformations on that data.
- Create a new model with the specified attributes. A client id (cid)
-is automatically generated and assigned for you.
+ Backbone Models are the basic data object in the framework –
+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
+performing computations and transformations on that data.
- var Model = Backbone.Model = function(attributes, options) {
- var attrs = attributes || {};
- options || (options = {});
- this.cid = _.uniqueId(this.cidPrefix);
- this.attributes = {};
- if (options.collection) this.collection = options.collection;
- if (options.parse) attrs = this.parse(attrs, options) || {};
- attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
- this.set(attrs, options);
- this.changed = {};
- this.initialize.apply(this, arguments);
- };
-
@@ -1048,11 +1048,24 @@ is automatically generated and assigned for you.
- Attach all inheritable methods to the Model prototype.
+ Create a new model with the specified attributes. A client id (cid)
+is automatically generated and assigned for you.
- _.extend(Model.prototype, Events, {
+ var Model = Backbone.Model = function(attributes, options) {
+ var attrs = attributes || {};
+ options || (options = {});
+ this.cid = _.uniqueId(this.cidPrefix);
+ this.attributes = {};
+ if (options.collection) this.collection = options.collection;
+ if (options.parse) attrs = this.parse(attrs, options) || {};
+ var defaults = _.result(this, 'defaults');
+ attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
+ this.set(attrs, options);
+ this.changed = {};
+ this.initialize.apply(this, arguments);
+ };
@@ -1063,11 +1076,11 @@ is automatically generated and assigned for you.
- A hash of attributes whose current and previous value differ.
+ Attach all inheritable methods to the Model prototype.
- changed: null,
+ _.extend(Model.prototype, Events, {
@@ -1078,11 +1091,11 @@ is automatically generated and assigned for you.
- The value returned during the last failed validation.
+ A hash of attributes whose current and previous value differ.
- validationError: null,
+ changed: null,
@@ -1093,6 +1106,21 @@ is automatically generated and assigned for you.
+ The value returned during the last failed validation.
+
+
+
+ validationError: null,
+
+
+
+
+
+
+
+
+ ¶
+
The default name for the JSON id attribute is "id". MongoDB and
CouchDB users may want to set this to "_id".
@@ -1103,11 +1131,11 @@ CouchDB users may want to set this to "_id".
-
+
The prefix is used to create the client id which is used to identify models locally.
You may want to override this if you’re experiencing name clashes with model ids.
@@ -1119,35 +1147,18 @@ You may want to override this if you’re experiencing name clashes with model i
-
-
-
-
- ¶
-
- Initialize is an empty function by default. Override it with your own
-initialization logic.
-
-
-
- initialize: function(){},
-
-
-
-
- Return a copy of the model’s attributes object.
+ Initialize is an empty function by default. Override it with your own
+initialization logic.
- toJSON: function(options) {
- return _.clone(this.attributes);
- },
+ initialize: function(){},
@@ -1158,13 +1169,12 @@ initialization logic.
- Proxy Backbone.sync by default — but override this if you need
-custom syncing semantics for this particular model.
+ Return a copy of the model’s attributes object.
- sync: function() {
- return Backbone.sync.apply(this, arguments);
+ toJSON: function(options) {
+ return _.clone(this.attributes);
},
@@ -1176,12 +1186,13 @@ custom syncing semantics for this particular model.
- Get the value of an attribute.
+ Proxy Backbone.sync by default – but override this if you need
+custom syncing semantics for this particular model.
- get: function(attr) {
- return this.attributes[attr];
+ sync: function() {
+ return Backbone.sync.apply(this, arguments);
},
@@ -1193,12 +1204,12 @@ custom syncing semantics for this particular model.
- Get the HTML-escaped value of an attribute.
+ Get the value of an attribute.
- escape: function(attr) {
- return _.escape(this.get(attr));
+ get: function(attr) {
+ return this.attributes[attr];
},
@@ -1210,13 +1221,12 @@ custom syncing semantics for this particular model.
- Returns true if the attribute contains a value that is not null
-or undefined.
+ Get the HTML-escaped value of an attribute.
- has: function(attr) {
- return this.get(attr) != null;
+ escape: function(attr) {
+ return _.escape(this.get(attr));
},
@@ -1228,12 +1238,13 @@ or undefined.
- Special-cased proxy to underscore’s _.matches method.
+ Returns true if the attribute contains a value that is not null
+or undefined.
- matches: function(attrs) {
- return !!_.iteratee(attrs, this)(this.attributes);
+ has: function(attr) {
+ return this.get(attr) != null;
},
@@ -1245,15 +1256,13 @@ or undefined.
- Set a hash of model attributes on the object, firing "change". This is
-the core primitive operation of a model, updating the data and notifying
-anyone who needs to know about the change in state. The heart of the beast.
+ Special-cased proxy to underscore’s _.matches method.
- set: function(key, val, options) {
- var attr, attrs, unset, changes, silent, changing, prev, current;
- if (key == null) return this;
+ matches: function(attrs) {
+ return !!_.iteratee(attrs, this)(this.attributes);
+ },
@@ -1264,11 +1273,30 @@ anyone who needs to know about the change in state. The heart of the beast.
+ Set a hash of model attributes on the object, firing "change". This is
+the core primitive operation of a model, updating the data and notifying
+anyone who needs to know about the change in state. The heart of the beast.
+
+
+
+ set: function(key, val, options) {
+ if (key == null) return this;
+
+
+
+
+
+
+
+
+ ¶
+
Handle both "key", value and {key: value} -style arguments.
- if (typeof key === 'object') {
+ var attrs;
+ if (typeof key === 'object') {
attrs = key;
options = val;
} else {
@@ -1280,11 +1308,11 @@ anyone who needs to know about the change in state. The heart of the beast.
-
+
Run validation.
@@ -1295,42 +1323,30 @@ anyone who needs to know about the change in state. The heart of the beast.
-
-
-
-
- ¶
-
- Extract attributes and options.
-
-
-
- unset = options.unset;
- silent = options.silent;
- changes = [];
- changing = this._changing;
- this._changing = true;
-
- if (!changing) {
- this._previousAttributes = _.clone(this.attributes);
- this.changed = {};
- }
- current = this.attributes, prev = this._previousAttributes;
-
-
-
-
- if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
+ var unset = options.unset;
+ var silent = options.silent;
+ var changes = [];
+ var changing = this._changing;
+ this._changing = true;
+
+ if (!changing) {
+ this._previousAttributes = _.clone(this.attributes);
+ this.changed = {};
+ }
+
+ var current = this.attributes;
+ var changed = this.changed;
+ var prev = this._previousAttributes;
@@ -1345,13 +1361,13 @@ anyone who needs to know about the change in state. The heart of the beast.
- for (attr in attrs) {
+ for (var attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
- this.changed[attr] = val;
+ changed[attr] = val;
} else {
- delete this.changed[attr];
+ delete changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
@@ -1365,6 +1381,21 @@ anyone who needs to know about the change in state. The heart of the beast.
+ Update the id.
+
+
+
+ if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);
+
+
+
+
+
+
+
+
+ ¶
+
Trigger all relevant attribute changes.
@@ -1379,11 +1410,11 @@ anyone who needs to know about the change in state. The heart of the beast.
-
+
You might be wondering why there’s a while loop here. Changes can
be recursively nested within "change" events.
@@ -1406,38 +1437,19 @@ be recursively nested within "change" events.
-
-
-
-
- ¶
-
- Remove an attribute from the model, firing "change". unset is a noop
-if the attribute doesn’t exist.
-
-
-
- unset: function(attr, options) {
- return this.set(attr, void 0, _.extend({}, options, {unset: true}));
- },
-
-
-
-
- Clear all attributes on the model, firing "change".
+ Remove an attribute from the model, firing "change". unset is a noop
+if the attribute doesn’t exist.
- clear: function(options) {
- var attrs = {};
- for (var key in this.attributes) attrs[key] = void 0;
- return this.set(attrs, _.extend({}, options, {unset: true}));
+ unset: function(attr, options) {
+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
@@ -1449,14 +1461,14 @@ if the attribute doesn’t exist.
- Determine if the model has changed since the last "change" event.
-If you specify an attribute name, determine if that attribute has changed.
+ Clear all attributes on the model, firing "change".
- hasChanged: function(attr) {
- if (attr == null) return !_.isEmpty(this.changed);
- return _.has(this.changed, attr);
+ clear: function(options) {
+ var attrs = {};
+ for (var key in this.attributes) attrs[key] = void 0;
+ return this.set(attrs, _.extend({}, options, {unset: true}));
},
@@ -1468,24 +1480,14 @@ If you specify an attribute name, determine if that attribute has changed.
- Return an object containing all the attributes that have changed, or
-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
-persisted to the server. Unset attributes will be set to undefined.
-You can also pass an attributes object to diff against the model,
-determining if there would be a change.
+ Determine if the model has changed since the last "change" event.
+If you specify an attribute name, determine if that attribute has changed.
- changedAttributes: function(diff) {
- if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
- var val, changed = false;
- var old = this._changing ? this._previousAttributes : this.attributes;
- for (var attr in diff) {
- if (_.isEqual(old[attr], (val = diff[attr]))) continue;
- (changed || (changed = {}))[attr] = val;
- }
- return changed;
+ hasChanged: function(attr) {
+ if (attr == null) return !_.isEmpty(this.changed);
+ return _.has(this.changed, attr);
},
@@ -1497,14 +1499,25 @@ determining if there would be a change.
- Get the previous value of an attribute, recorded at the time the last
-"change" event was fired.
+ Return an object containing all the attributes that have changed, or
+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
+persisted to the server. Unset attributes will be set to undefined.
+You can also pass an attributes object to diff against the model,
+determining if there would be a change.
- previous: function(attr) {
- if (attr == null || !this._previousAttributes) return null;
- return this._previousAttributes[attr];
+ changedAttributes: function(diff) {
+ if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
+ var old = this._changing ? this._previousAttributes : this.attributes;
+ var changed = {};
+ for (var attr in diff) {
+ var val = diff[attr];
+ if (_.isEqual(old[attr], val)) continue;
+ changed[attr] = val;
+ }
+ return _.size(changed) ? changed : false;
},
@@ -1516,13 +1529,14 @@ determining if there would be a change.
- Get all of the attributes of the model at the time of the previous
-"change" event.
+ Get the previous value of an attribute, recorded at the time the last
+"change" event was fired.
- previousAttributes: function() {
- return _.clone(this._previousAttributes);
+ previous: function(attr) {
+ if (attr == null || !this._previousAttributes) return null;
+ return this._previousAttributes[attr];
},
@@ -1534,23 +1548,13 @@ determining if there would be a change.
- Fetch the model from the server, merging the response with the model’s
-local attributes. Any changed attributes will trigger a “change” event.
+ Get all of the attributes of the model at the time of the previous
+"change" event.
- fetch: function(options) {
- options = options ? _.clone(options) : {};
- if (options.parse === void 0) options.parse = true;
- var model = this;
- var success = options.success;
- options.success = function(resp) {
- if (!model.set(model.parse(resp, options), options)) return false;
- if (success) success.call(options.context, model, resp, options);
- model.trigger('sync', model, resp, options);
- };
- wrapError(this, options);
- return this.sync('read', this, options);
+ previousAttributes: function() {
+ return _.clone(this._previousAttributes);
},
@@ -1562,14 +1566,24 @@ local attributes. Any changed attributes will trigger a “change” event.
- Set a hash of model attributes, and sync the model to the server.
-If the server returns an attributes hash that differs, the model’s
-state will be set again.
+ Fetch the model from the server, merging the response with the model’s
+local attributes. Any changed attributes will trigger a “change” event.
- save: function(key, val, options) {
- var attrs, method, xhr, attributes = this.attributes, wait;
+ fetch: function(options) {
+ options = _.extend({parse: true}, options);
+ var model = this;
+ var success = options.success;
+ options.success = function(resp) {
+ var serverAttrs = options.parse ? model.parse(resp, options) : resp;
+ if (!model.set(serverAttrs, options)) return false;
+ if (success) success.call(options.context, model, resp, options);
+ model.trigger('sync', model, resp, options);
+ };
+ wrapError(this, options);
+ return this.sync('read', this, options);
+ },
@@ -1580,19 +1594,13 @@ state will be set again.
- Handle both "key", value and {key: value} -style arguments.
+ Set a hash of model attributes, and sync the model to the server.
+If the server returns an attributes hash that differs, the model’s
+state will be set again.
- if (key == null || typeof key === 'object') {
- attrs = key;
- options = val;
- } else {
- (attrs = {})[key] = val;
- }
-
- options = _.extend({validate: true}, options);
- wait = options.wait;
+ save: function(key, val, options) {
@@ -1603,17 +1611,20 @@ state will be set again.
- 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.
+ Handle both "key", value and {key: value} -style arguments.
- if (attrs && !wait) {
- if (!this.set(attrs, options)) return false;
+ var attrs;
+ if (key == null || typeof key === 'object') {
+ attrs = key;
+ options = val;
} else {
- if (!this._validate(attrs, options)) return false;
- }
+ (attrs = {})[key] = val;
+ }
+
+ options = _.extend({validate: true, parse: true}, options);
+ var wait = options.wait;
@@ -1624,12 +1635,16 @@ the model will be valid when the attributes, if any, are set.
- Set temporary attributes if {wait: true}.
+ 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 && wait) {
- this.attributes = _.extend({}, attributes, attrs);
+ if (attrs && !wait) {
+ if (!this.set(attrs, options)) return false;
+ } else if (!this._validate(attrs, options)) {
+ return false;
}
@@ -1646,10 +1661,10 @@ updated with the server-side state.
- if (options.parse === void 0) options.parse = true;
- var model = this;
+ var model = this;
var success = options.success;
- options.success = function(resp) {
+ var attributes = this.attributes;
+ options.success = function(resp) {
@@ -1666,18 +1681,12 @@ updated with the server-side state.
model.attributes = attributes;
var serverAttrs = options.parse ? model.parse(resp, options) : resp;
- if (wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
- if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
- return false;
- }
+ if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
+ if (serverAttrs && !model.set(serverAttrs, options)) return false;
if (success) success.call(options.context, model, resp, options);
model.trigger('sync', model, resp, options);
};
- wrapError(this, options);
-
- method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
- if (method === 'patch' && !options.attrs) options.attrs = attrs;
- xhr = this.sync(method, this, options);
+ wrapError(this, options);
@@ -1688,14 +1697,15 @@ updated with the server-side state.
- Restore attributes.
+ Set temporary attributes if {wait: true} to properly find new ids.
- if (attrs && wait) this.attributes = attributes;
+ if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);
- return xhr;
- },
+ var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
+ if (method === 'patch' && !options.attrs) options.attrs = attrs;
+ var xhr = this.sync(method, this, options);
@@ -1706,24 +1716,42 @@ updated with the server-side state.
+ Restore attributes.
+
+
+
+ this.attributes = attributes;
+
+ return xhr;
+ },
+
+
+
+
+
+
+
+
+ ¶
+
Destroy this model on the server if it was already persisted.
Optimistically removes the model from its collection, if it has one.
If wait: true is passed, waits for the server to respond before removal.
- destroy: function(options) {
+ destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var wait = options.wait;
- var destroy = function() {
+ var destroy = function() {
model.stopListening();
model.trigger('destroy', model, model.collection, options);
};
- options.success = function(resp) {
+ options.success = function(resp) {
if (wait) destroy();
if (success) success.call(options.context, model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
@@ -1743,44 +1771,26 @@ If wait: true is passed, waits for the server to respond before rem
-
-
-
-
- ¶
-
- Default URL for the model’s representation on the server — if you’re
-using Backbone’s restful methods, override this to change the endpoint
-that will be called.
-
-
-
- url: function() {
- var base =
- _.result(this, 'urlRoot') ||
- _.result(this.collection, 'url') ||
- urlError();
- if (this.isNew()) return base;
- var id = this.id || this.attributes[this.idAttribute];
- return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(id);
- },
-
-
-
-
- parse converts a response into the hash of attributes to be set on
-the model. The default implementation is just to pass the response along.
+ Default URL for the model’s representation on the server – if you’re
+using Backbone’s restful methods, override this to change the endpoint
+that will be called.
- parse: function(resp, options) {
- return resp;
+ url: function() {
+ var base =
+ _.result(this, 'urlRoot') ||
+ _.result(this.collection, 'url') ||
+ urlError();
+ if (this.isNew()) return base;
+ var id = this.get(this.idAttribute);
+ return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
},
@@ -1792,12 +1802,13 @@ the model. The default implementation is just to pass the response along.
- Create a new model with identical attributes to this one.
+ parse converts a response into the hash of attributes to be set on
+the model. The default implementation is just to pass the response along.
- clone: function() {
- return new this.constructor(this.attributes);
+ parse: function(resp, options) {
+ return resp;
},
@@ -1809,12 +1820,12 @@ the model. The default implementation is just to pass the response along.
- A model is new if it has never been saved to the server, and lacks an id.
+ Create a new model with identical attributes to this one.
- isNew: function() {
- return !this.has(this.idAttribute);
+ clone: function() {
+ return new this.constructor(this.attributes);
},
@@ -1826,12 +1837,12 @@ the model. The default implementation is just to pass the response along.
- Check if the model is currently in a valid state.
+ A model is new if it has never been saved to the server, and lacks an id.
- isValid: function(options) {
- return this._validate({}, _.extend(options || {}, { validate: true }));
+ isNew: function() {
+ return !this.has(this.idAttribute);
},
@@ -1843,12 +1854,29 @@ the model. The default implementation is just to pass the response along.
+ Check if the model is currently in a valid state.
+
+
+
+ isValid: function(options) {
+ return this._validate({}, _.extend({}, options, {validate: true}));
+ },
+
+
+
+
+
+
+
+
+ ¶
+
Run validation against the next complete set of model attributes,
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;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
@@ -1862,33 +1890,19 @@ returning true if all is well. Otherwise, fire an "inval
-
-
-
-
- ¶
-
- Underscore methods that we want to implement on the Model.
-
-
-
- var modelMethods = { keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
- omit: 0, chain: 1, isEmpty: 1 };
-
-
-
-
- Mix in each Underscore method as a proxy to Model#attributes.
+ Underscore methods that we want to implement on the Model, mapped to the
+number of arguments they take.
- addUnderscoreMethods(Model, modelMethods, 'attributes');
+ var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
+ omit: 0, chain: 1, isEmpty: 1};
@@ -1899,10 +1913,12 @@ returning true if all is well. Otherwise, fire an "inval
- Backbone.Collection
+ Mix in each Underscore method as a proxy to Model#attributes.
+ addUnderscoreMethods(Model, modelMethods, 'attributes');
+
@@ -1912,7 +1928,8 @@ returning true if all is well. Otherwise, fire an "inval
-
+ Backbone.Collection
+
@@ -1924,13 +1941,7 @@ returning true if all is well. Otherwise, fire an "inval
- If models tend to represent a single row of data, a Backbone Collection is
-more analogous to a table full of data … or a small slice or page of that
-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
-belonging to this particular author, and so on. Collections maintain
-indexes of their models, both in order, and for lookup by id.
-
+
@@ -1942,13 +1953,31 @@ indexes of their models, both in order, and for lookup by id.
+ If models tend to represent a single row of data, a Backbone Collection is
+more analogous to a table full of data … or a small slice or page of that
+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
+belonging to this particular author, and so on. Collections maintain
+indexes of their models, both in order, and for lookup by id.
+
+
+
+
+
+
+
+
+
+
+ ¶
+
Create a new Collection, perhaps to contain a specific type of model.
If a comparator is specified, the Collection will maintain
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 = {});
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
@@ -1960,11 +1989,11 @@ its models in sort order, as they’re added and removed.
-
+
Default options for Collection#set.
@@ -1976,11 +2005,34 @@ its models in sort order, as they’re added and removed.
-
+
+
+ var splice = function(array, insert, at) {
+ at = Math.min(Math.max(at, 0), array.length);
+ var tail = Array(array.length - at);
+ var length = insert.length;
+ 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 < tail.length; i++) array[i + length + at] = tail[i];
+ };
+
+
+
+
+
+
+
+
+ ¶
Define the Collection’s inheritable methods.
@@ -1991,11 +2043,11 @@ its models in sort order, as they’re added and removed.
-
+
The default model for a collection is just a Backbone.Model.
This should be overridden in most cases.
@@ -2007,53 +2059,18 @@ This should be overridden in most cases.
-
-
-
-
- ¶
-
- Initialize is an empty function by default. Override it with your own
-initialization logic.
-
-
-
- initialize: function(){},
-
-
-
-
-
-
-
-
- ¶
-
- The JSON representation of a Collection is an array of the
-models’ attributes.
-
-
-
- toJSON: function(options) {
- return this.map(function(model){ return model.toJSON(options); });
- },
-
-
-
-
- Proxy Backbone.sync by default.
+ Initialize is an empty function by default. Override it with your own
+initialization logic.
- sync: function() {
- return Backbone.sync.apply(this, arguments);
- },
+ initialize: function(){},
@@ -2064,12 +2081,13 @@ models’ attributes.
- Add a model, or list of models to the set.
+ The JSON representation of a Collection is an array of the
+models’ attributes.
- add: function(models, options) {
- return this.set(models, _.extend({merge: false}, options, addOptions));
+ toJSON: function(options) {
+ return this.map(function(model) { return model.toJSON(options); });
},
@@ -2081,17 +2099,12 @@ models’ attributes.
- Remove a model, or a list of models from the set.
+ Proxy Backbone.sync by default.
- remove: function(models, options) {
- var singular = !_.isArray(models), removed;
- models = singular ? [models] : _.clone(models);
- options || (options = {});
- removed = this._removeModels(models, options);
- if (!options.silent && removed) this.trigger('update', this, options);
- return singular ? models[0] : models;
+ sync: function() {
+ return Backbone.sync.apply(this, arguments);
},
@@ -2103,28 +2116,15 @@ models’ attributes.
- 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
-already exist in the collection, as necessary. Similar to Model#set,
-the core operation for updating the data contained by the collection.
+ Add a model, or list of models to the set. models may be Backbone
+Models or raw JavaScript objects to be converted to Models, or any
+combination of the two.
- set: function(models, options) {
- options = _.defaults({}, options, setOptions);
- if (options.parse) models = this.parse(models, options);
- var singular = !_.isArray(models);
- models = singular ? (models ? [models] : []) : models.slice();
- var id, model, attrs, existing, sort;
- var at = options.at;
- if (at != null) at = +at;
- if (at < 0) at += this.length + 1;
- 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;
- var orderChanged = false;
+ add: function(models, options) {
+ return this.set(models, _.extend({merge: false}, options, addOptions));
+ },
@@ -2135,13 +2135,21 @@ the core operation for updating the data contained by the collection.
- Turn bare objects into model references, and prevent invalid models
-from being added.
+ Remove a model, or a list of models from the set.
- for (var i = 0; i < models.length; i++) {
- attrs = models[i];
+ remove: function(models, options) {
+ options = _.extend({}, options);
+ var singular = !_.isArray(models);
+ models = singular ? [models] : models.slice();
+ var removed = this._removeModels(models, options);
+ if (!options.silent && removed.length) {
+ options.changes = {added: [], merged: [], removed: removed};
+ this.trigger('update', this, options);
+ }
+ return singular ? removed[0] : removed;
+ },
@@ -2152,20 +2160,42 @@ from being added.
- If a duplicate is found, prevent it from being added and
-optionally merge it into the existing model.
+ 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
+already exist in the collection, as necessary. Similar to Model#set,
+the core operation for updating the data contained by the collection.
- if (existing = this.get(attrs)) {
- if (remove) modelMap[existing.cid] = true;
- if (merge && attrs !== existing) {
- attrs = this._isModel(attrs) ? attrs.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;
+ set: function(models, options) {
+ if (models == null) return;
+
+ options = _.extend({}, setOptions, options);
+ if (options.parse && !this._isModel(models)) {
+ models = this.parse(models, options) || [];
+ }
+
+ var singular = !_.isArray(models);
+ models = singular ? [models] : models.slice();
+
+ var at = options.at;
+ if (at != null) at = +at;
+ if (at > this.length) at = this.length;
+ if (at < 0) at += this.length + 1;
+
+ var set = [];
+ var toAdd = [];
+ var toMerge = [];
+ var toRemove = [];
+ var modelMap = {};
+
+ var add = options.add;
+ var merge = options.merge;
+ var remove = options.remove;
+
+ var sort = false;
+ var sortable = this.comparator && at == null && options.sort !== false;
+ var sortAttr = _.isString(this.comparator) ? this.comparator : null;
@@ -2176,16 +2206,14 @@ optionally merge it into the existing model.
- If this is a new, valid model, push it to the toAdd list.
+ Turn bare objects into model references, and prevent invalid models
+from being added.
- } else if (add) {
- model = models[i] = this._prepareModel(attrs, options);
- if (!model) continue;
- toAdd.push(model);
- this._addReference(model, options);
- }
+ var model, i;
+ for (i = 0; i < models.length; i++) {
+ model = models[i];
@@ -2196,15 +2224,25 @@ optionally merge it into the existing model.
- Do not add multiple models with the same id.
+ If a duplicate is found, prevent it from being added and
+optionally merge it into the existing model.
- model = existing || model;
- if (!model) continue;
- id = this.modelId(model.attributes);
- if (order && (model.isNew() || !modelMap[id])) {
- order.push(model);
+ var existing = this.get(model);
+ if (existing) {
+ if (merge && model !== existing) {
+ var attrs = this._isModel(model) ? model.attributes : model;
+ if (options.parse) attrs = existing.parse(attrs, options);
+ existing.set(attrs, options);
+ toMerge.push(existing);
+ if (sortable && !sort) sort = existing.hasChanged(sortAttr);
+ }
+ if (!modelMap[existing.cid]) {
+ modelMap[existing.cid] = true;
+ set.push(existing);
+ }
+ models[i] = existing;
@@ -2215,14 +2253,19 @@ optionally merge it into the existing model.
- Check to see if this is actually a new model at this index.
+ If this is a new, valid model, push it to the toAdd list.
- orderChanged = orderChanged || !this.models[i] || model.cid !== this.models[i].cid;
+ } else if (add) {
+ model = models[i] = this._prepareModel(model, options);
+ if (model) {
+ toAdd.push(model);
+ this._addReference(model, options);
+ modelMap[model.cid] = true;
+ set.push(model);
+ }
}
-
- modelMap[id] = true;
}
@@ -2234,13 +2277,14 @@ optionally merge it into the existing model.
- Remove nonexistent models if appropriate.
+ Remove stale models.
if (remove) {
- for (var i = 0; i < this.length; i++) {
- if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
+ for (i = 0; i < this.length; i++) {
+ model = this.models[i];
+ if (!modelMap[model.cid]) toRemove.push(model);
}
if (toRemove.length) this._removeModels(toRemove, options);
}
@@ -2258,20 +2302,19 @@ optionally merge it into the existing model.
- if (toAdd.length || orderChanged) {
+ var orderChanged = false;
+ var replace = !sortable && add && remove;
+ if (set.length && replace) {
+ orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
+ return m !== set[index];
+ });
+ this.models.length = 0;
+ splice(this.models, set, 0);
+ this.length = this.models.length;
+ } else if (toAdd.length) {
if (sortable) sort = true;
- this.length += toAdd.length;
- if (at != null) {
- for (var i = 0; i < toAdd.length; i++) {
- this.models.splice(at + i, 0, toAdd[i]);
- }
- } else {
- if (order) this.models.length = 0;
- var orderedModels = order || toAdd;
- for (var i = 0; i < orderedModels.length; i++) {
- this.models.push(orderedModels[i]);
- }
- }
+ splice(this.models, toAdd, at == null ? this.length : at);
+ this.length = this.models.length;
}
@@ -2298,18 +2341,25 @@ optionally merge it into the existing model.
- Unless silenced, it’s time to fire all appropriate add/sort events.
+ Unless silenced, it’s time to fire all appropriate add/sort/update events.
if (!options.silent) {
- var addOpts = at != null ? _.clone(options) : options;
- for (var i = 0; i < toAdd.length; i++) {
- if (at != null) addOpts.index = at + i;
- (model = toAdd[i]).trigger('add', model, this, addOpts);
+ for (i = 0; i < toAdd.length; i++) {
+ if (at != null) options.index = at + i;
+ model = toAdd[i];
+ model.trigger('add', model, this, options);
}
if (sort || orderChanged) this.trigger('sort', this, options);
- if (toAdd.length || toRemove.length) this.trigger('update', this, options);
+ if (toAdd.length || toRemove.length || toMerge.length) {
+ options.changes = {
+ added: toAdd,
+ removed: toRemove,
+ merged: toMerge
+ };
+ this.trigger('update', this, options);
+ }
}
@@ -2344,7 +2394,7 @@ Useful for bulk operations and optimizations.
- reset: function(models, options) {
+ reset: function(models, options) {
options = options ? _.clone(options) : {};
for (var i = 0; i < this.models.length; i++) {
this._removeReference(this.models[i], options);
@@ -2369,7 +2419,7 @@ Useful for bulk operations and optimizations.
- push: function(model, options) {
+ push: function(model, options) {
return this.add(model, _.extend({at: this.length}, options));
},
@@ -2386,10 +2436,9 @@ Useful for bulk operations and optimizations.
- pop: function(options) {
+ pop: function(options) {
var model = this.at(this.length - 1);
- this.remove(model, options);
- return model;
+ return this.remove(model, options);
},
@@ -2405,7 +2454,7 @@ Useful for bulk operations and optimizations.
- unshift: function(model, options) {
+ unshift: function(model, options) {
return this.add(model, _.extend({at: 0}, options));
},
@@ -2422,10 +2471,9 @@ Useful for bulk operations and optimizations.
- shift: function(options) {
+ shift: function(options) {
var model = this.at(0);
- this.remove(model, options);
- return model;
+ return this.remove(model, options);
},
@@ -2441,7 +2489,7 @@ Useful for bulk operations and optimizations.
- slice: function() {
+ slice: function() {
return slice.apply(this.models, arguments);
},
@@ -2454,14 +2502,16 @@ Useful for bulk operations and optimizations.
- 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;
- var id = this.modelId(this._isModel(obj) ? obj.attributes : obj);
- return this._byId[obj] || this._byId[id] || this._byId[obj.cid];
+ return this._byId[obj] ||
+ this._byId[this.modelId(obj.attributes || obj)] ||
+ obj.cid && this._byId[obj.cid];
},
@@ -2473,13 +2523,12 @@ Useful for bulk operations and optimizations.
- Get the model at the given index.
+ Returns true if the model is in the collection.
- at: function(index) {
- if (index < 0) index += this.length;
- return this.models[index];
+ has: function(obj) {
+ return this.get(obj) != null;
},
@@ -2491,16 +2540,13 @@ Useful for bulk operations and optimizations.
- Return models with matching attributes. Useful for simple cases of
-filter.
+ Get the model at the given index.
- where: function(attrs, first) {
- var matches = _.matches(attrs);
- return this[first ? 'find' : 'filter'](function(model) {
- return matches(model.attributes);
- });
+ at: function(index) {
+ if (index < 0) index += this.length;
+ return this.models[index];
},
@@ -2512,13 +2558,13 @@ Useful for bulk operations and optimizations.
- Return the first model with matching attributes. Useful for simple cases
-of find.
+ Return models with matching attributes. Useful for simple cases of
+filter.
- findWhere: function(attrs) {
- return this.where(attrs, true);
+ where: function(attrs, first) {
+ return this[first ? 'find' : 'filter'](attrs);
},
@@ -2530,15 +2576,14 @@ of find.
- Force the collection to re-sort itself. You don’t need to call this under
-normal circumstances, as the set will maintain sort order as each item
-is added.
+ Return the first model with matching attributes. Useful for simple cases
+of find.
- sort: function(options) {
- if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
- options || (options = {});
+ findWhere: function(attrs) {
+ return this.where(attrs, true);
+ },
@@ -2549,19 +2594,19 @@ is added.
- Run sort based on type of comparator.
+ Force the collection to re-sort itself. You don’t need to call this under
+normal circumstances, as the set will maintain sort order as each item
+is added.
- if (_.isString(this.comparator) || this.comparator.length === 1) {
- this.models = this.sortBy(this.comparator, this);
- } else {
- this.models.sort(_.bind(this.comparator, this));
- }
+ sort: function(options) {
+ var comparator = this.comparator;
+ if (!comparator) throw new Error('Cannot sort a set without a comparator');
+ options || (options = {});
- if (!options.silent) this.trigger('sort', this, options);
- return this;
- },
+ var length = comparator.length;
+ if (_.isFunction(comparator)) comparator = _.bind(comparator, this);
@@ -2572,12 +2617,17 @@ is added.
- Pluck an attribute from each model in the collection.
+ Run sort based on type of comparator.
- pluck: function(attr) {
- return _.invoke(this.models, 'get', attr);
+ if (length === 1 || _.isString(comparator)) {
+ this.models = this.sortBy(comparator);
+ } else {
+ this.models.sort(comparator);
+ }
+ if (!options.silent) this.trigger('sort', this, options);
+ return this;
},
@@ -2589,18 +2639,34 @@ is added.
+ Pluck an attribute from each model in the collection.
+
+
+
+ pluck: function(attr) {
+ return this.map(attr + '');
+ },
+
+
+
+
+
+
+
+
+ ¶
+
Fetch the default set of models for this collection, resetting the
collection when they arrive. If reset: true is passed, the response
data will be passed through the reset method instead of set.
- fetch: function(options) {
- options = options ? _.clone(options) : {};
- if (options.parse === void 0) options.parse = true;
+ fetch: function(options) {
+ options = _.extend({parse: true}, options);
var success = options.success;
var collection = this;
- options.success = function(resp) {
+ options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success.call(options.context, collection, resp, options);
@@ -2613,11 +2679,11 @@ data will be passed through the reset method instead of set
-
+
Create a new instance of a model in this collection. Add the model to the
collection immediately, unless wait: true is passed, in which case we
@@ -2625,16 +2691,17 @@ wait for the server to agree.
- create: function(model, options) {
+ create: function(model, options) {
options = options ? _.clone(options) : {};
var wait = options.wait;
- if (!(model = this._prepareModel(model, options))) return false;
+ model = this._prepareModel(model, options);
+ if (!model) return false;
if (!wait) this.add(model, options);
var collection = this;
var success = options.success;
- options.success = function(model, resp, callbackOpts) {
- if (wait) collection.add(model, callbackOpts);
- if (success) success.call(callbackOpts.context, model, resp, callbackOpts);
+ options.success = function(m, resp, callbackOpts) {
+ if (wait) collection.add(m, callbackOpts);
+ if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
};
model.save(null, options);
return model;
@@ -2643,39 +2710,19 @@ wait for the server to agree.
-
-
-
-
- ¶
-
- parse converts a response into a list of models to be added to the
-collection. The default implementation is just to pass it through.
-
-
-
- parse: function(resp, options) {
- return resp;
- },
-
-
-
-
- Create a new collection with an identical list of models as this one.
+ parse converts a response into a list of models to be added to the
+collection. The default implementation is just to pass it through.
- clone: function() {
- return new this.constructor(this.models, {
- model: this.model,
- comparator: this.comparator
- });
+ parse: function(resp, options) {
+ return resp;
},
@@ -2687,12 +2734,15 @@ collection. The default implementation is just to pass it through.
- Define how to uniquely identify models in the collection.
+ Create a new collection with an identical list of models as this one.
- modelId: function (attrs) {
- return attrs[this.model.prototype.idAttribute || 'id'];
+ clone: function() {
+ return new this.constructor(this.models, {
+ model: this.model,
+ comparator: this.comparator
+ });
},
@@ -2704,15 +2754,12 @@ collection. The default implementation is just to pass it through.
- Private method to reset all internal state. Called when the collection
-is first initialized or reset.
+ Define how to uniquely identify models in the collection.
- _reset: function() {
- this.length = 0;
- this.models = [];
- this._byId = {};
+ modelId: function(attrs) {
+ return attrs[this.model.prototype.idAttribute || 'id'];
},
@@ -2724,12 +2771,32 @@ is first initialized or reset.
+ Private method to reset all internal state. Called when the collection
+is first initialized or reset.
+
+
+
+ _reset: function() {
+ this.length = 0;
+ this.models = [];
+ this._byId = {};
+ },
+
+
+
+
+
+
+
+
+ ¶
+
Prepare a hash of attributes (or other model) to be added to this
collection.
- _prepareModel: function(attrs, options) {
+ _prepareModel: function(attrs, options) {
if (this._isModel(attrs)) {
if (!attrs.collection) attrs.collection = this;
return attrs;
@@ -2745,54 +2812,25 @@ collection.
-
-
-
-
- ¶
-
- Internal method called by both remove and set. Does not trigger any
-additional events. Returns true if anything was actually removed.
-
-
-
- _removeModels: function(models, options) {
- var i, l, index, model, removed = false;
- for (var i = 0, j = 0; i < models.length; i++) {
- var model = models[i] = this.get(models[i]);
- if (!model) continue;
- var id = this.modelId(model.attributes);
- if (id != null) delete this._byId[id];
- delete this._byId[model.cid];
- var index = this.indexOf(model);
- this.models.splice(index, 1);
- this.length--;
- if (!options.silent) {
- options.index = index;
- model.trigger('remove', model, this, options);
- }
- models[j++] = model;
- this._removeReference(model, options);
- removed = true;
- }
-
-
-
-
- We only need to slice if models array should be smaller, which is
-caused by some models not actually getting removed.
+ Internal method called by both remove and set.
- if (models.length !== j) models = models.slice(0, j);
- return removed;
- },
+ _removeModels: function(models, options) {
+ var removed = [];
+ for (var i = 0; i < models.length; i++) {
+ var model = this.get(models[i]);
+ if (!model) continue;
+
+ var index = this.indexOf(model);
+ this.models.splice(index, 1);
+ this.length--;
@@ -2803,13 +2841,24 @@ caused by some models not actually getting removed.
- Method for checking whether an object should be considered a model for
-the purposes of adding to the collection.
+ Remove references before triggering ‘remove’ event to prevent an
+infinite loop. #3693
- _isModel: function (model) {
- return model instanceof Model;
+ delete this._byId[model.cid];
+ var id = this.modelId(model.attributes);
+ if (id != null) delete this._byId[id];
+
+ if (!options.silent) {
+ options.index = index;
+ model.trigger('remove', model, this, options);
+ }
+
+ removed.push(model);
+ this._removeReference(model, options);
+ }
+ return removed;
},
@@ -2821,15 +2870,13 @@ the purposes of adding to the collection.
- Internal method to create a model’s ties to a collection.
+ Method for checking whether an object should be considered a model for
+the purposes of adding to the collection.
- _addReference: function(model, options) {
- this._byId[model.cid] = model;
- var id = this.modelId(model.attributes);
- if (id != null) this._byId[id] = model;
- model.on('all', this._onModelEvent, this);
+ _isModel: function(model) {
+ return model instanceof Model;
},
@@ -2841,13 +2888,15 @@ the purposes of adding to the collection.
- Internal method to sever a model’s ties to a collection.
+ Internal method to create a model’s ties to a collection.
- _removeReference: function(model, options) {
- if (this === model.collection) delete model.collection;
- model.off('all', this._onModelEvent, this);
+ _addReference: function(model, options) {
+ this._byId[model.cid] = model;
+ var id = this.modelId(model.attributes);
+ if (id != null) this._byId[id] = model;
+ model.on('all', this._onModelEvent, this);
},
@@ -2859,28 +2908,17 @@ the purposes of adding to the collection.
- Internal method called every time a model in the set fires an event.
-Sets need to update their indexes when models change ids. All other
-events simply proxy through. “add” and “remove” events that originate
-in other collections are ignored.
+ Internal method to sever a model’s ties to a collection.
- _onModelEvent: function(event, model, collection, options) {
- if ((event === 'add' || event === 'remove') && collection !== this) return;
- if (event === 'destroy') this.remove(model, options);
- if (event === 'change') {
- var prevId = this.modelId(model.previousAttributes());
- var id = this.modelId(model.attributes);
- if (prevId !== id) {
- if (prevId != null) delete this._byId[prevId];
- if (id != null) this._byId[id] = model;
- }
- }
- this.trigger.apply(this, arguments);
- }
-
- });
+ _removeReference: function(model, options) {
+ delete this._byId[model.cid];
+ var id = this.modelId(model.attributes);
+ if (id != null) delete this._byId[id];
+ if (this === model.collection) delete model.collection;
+ model.off('all', this._onModelEvent, this);
+ },
@@ -2891,19 +2929,30 @@ in other collections are ignored.
- Underscore methods that we want to implement on the Collection.
-90% of the core usefulness of Backbone Collections is actually implemented
-right here:
+ Internal method called every time a model in the set fires an event.
+Sets need to update their indexes when models change ids. All other
+events simply proxy through. “add” and “remove” events that originate
+in other collections are ignored.
- var collectionMethods = { forEach: 3, each: 3, map: 3, collect: 3, reduce: 4,
- foldl: 4, inject: 4, reduceRight: 4, foldr: 4, find: 3, detect: 3, filter: 3,
- select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 2,
- contains: 2, invoke: 2, max: 3, min: 3, toArray: 1, size: 1, first: 3,
- head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
- without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
- isEmpty: 1, chain: 1, sample: 3, partition: 3 };
+ _onModelEvent: function(event, model, collection, options) {
+ if (model) {
+ if ((event === 'add' || event === 'remove') && collection !== this) return;
+ if (event === 'destroy') this.remove(model, options);
+ if (event === 'change') {
+ var prevId = this.modelId(model.previousAttributes());
+ var id = this.modelId(model.attributes);
+ if (prevId !== id) {
+ if (prevId != null) delete this._byId[prevId];
+ if (id != null) this._byId[id] = model;
+ }
+ }
+ }
+ this.trigger.apply(this, arguments);
+ }
+
+ });
@@ -2914,11 +2963,20 @@ right here:
- Mix in each Underscore method as a proxy to Collection#models.
+ Underscore methods that we want to implement on the Collection.
+90% of the core usefulness of Backbone Collections is actually implemented
+right here:
- addUnderscoreMethods(Collection, collectionMethods, 'models');
+ var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
+ foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
+ select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
+ contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
+ head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
+ without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
+ isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
+ sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};
@@ -2929,11 +2987,11 @@ right here:
- Underscore methods that take a property name as an argument.
+ Mix in each Underscore method as a proxy to Collection#models.
- var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
+ addUnderscoreMethods(Collection, collectionMethods, 'models');
@@ -2944,20 +3002,10 @@ right here:
- Use attributes instead of properties.
+ Backbone.View
- _.each(attributeMethods, function(method) {
- if (!_[method]) return;
- Collection.prototype[method] = function(value, context) {
- var iterator = _.isFunction(value) ? value : function(model) {
- return model.get(value);
- };
- return _[method](this.models, iterator, context);
- };
- });
-
@@ -2967,8 +3015,7 @@ right here:
- Backbone.View
-
+
@@ -2980,18 +3027,6 @@ right here:
-
-
-
-
-
-
-
-
-
-
- ¶
-
Backbone Views are almost more convention than they are actual code. A View
is simply a JavaScript object that represents a logical chunk of UI in the
DOM. This might be a single item, an entire list, a sidebar or panel, or
@@ -3005,20 +3040,19 @@ react to specific changes in the state of your models.
-
+
Creating a Backbone.View creates its initial element outside of the DOM,
if an existing element is not provided…
- var View = Backbone.View = function(options) {
+ var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
- options || (options = {});
_.extend(this, _.pick(options, viewOptions));
this._ensureElement();
this.initialize.apply(this, arguments);
@@ -3027,11 +3061,11 @@ if an existing element is not provided…
-
+
Cached regex to split keys for delegate.
@@ -3042,13 +3076,13 @@ if an existing element is not provided…
-
+
@@ -3057,11 +3091,11 @@ if an existing element is not provided…
-
+
Set up all inheritable Backbone.View properties and methods.
@@ -3072,11 +3106,11 @@ if an existing element is not provided…
-
+
The default tagName of a View’s element is "div".
@@ -3087,36 +3121,55 @@ if an existing element is not provided…
-
+
jQuery delegate for element lookup, scoped to DOM elements within the
current view. This should be preferred to global lookups where possible.
- $: function(selector) {
+ $: function(selector) {
return this.$el.find(selector);
},
+
+
+
+
+ ¶
+
+ Initialize is an empty function by default. Override it with your own
+initialization logic.
+
+
+
+ initialize: function(){},
+
+
+
+
- Initialize is an empty function by default. Override it with your own
-initialization logic.
+ render is the core function that your view should override, in order
+to populate its element (this.el), with the appropriate HTML. The
+convention is for render to always return this.
- initialize: function(){},
+ render: function() {
+ return this;
+ },
@@ -3127,13 +3180,14 @@ initialization logic.
- render is the core function that your view should override, in order
-to populate its element (this.el), with the appropriate HTML. The
-convention is for render to always return this.
+ Remove this view by taking the element out of the DOM, and removing any
+applicable Backbone.Events listeners.
- render: function() {
+ remove: function() {
+ this._removeElement();
+ this.stopListening();
return this;
},
@@ -3146,15 +3200,14 @@ convention is for render to always return this.
¶
- Remove this view by taking the element out of the DOM, and removing any
-applicable Backbone.Events listeners.
+ Remove this view’s element from the document and all event listeners
+attached to it. Exposed for subclasses using an alternative DOM
+manipulation API.
- remove: function() {
- this._removeElement();
- this.stopListening();
- return this;
+ _removeElement: function() {
+ this.$el.remove();
},
@@ -3166,14 +3219,16 @@ applicable Backbone.Events listeners.
- Remove this view’s element from the document and all event listeners
-attached to it. Exposed for subclasses using an alternative DOM
-manipulation API.
+ Change the view’s element (this.el property) and re-delegate the
+view’s events on the new element.
- _removeElement: function() {
- this.$el.remove();
+ setElement: function(element) {
+ this.undelegateEvents();
+ this._setElement(element);
+ this.delegateEvents();
+ return this;
},
@@ -3185,16 +3240,17 @@ manipulation API.
- Change the view’s element (this.el property) and re-delegate the
-view’s events on the new element.
+ Creates the this.el and this.$el references for this view using the
+given el. el can be a CSS selector or an HTML string, a jQuery
+context or an element. Subclasses can override this to utilize an
+alternative DOM manipulation API and are only required to set the
+this.el property.
- setElement: function(element) {
- this.undelegateEvents();
- this._setElement(element);
- this.delegateEvents();
- return this;
+ _setElement: function(el) {
+ this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
+ this.el = this.$el[0];
},
@@ -3206,17 +3262,31 @@ view’s events on the new element.
- Creates the this.el and this.$el references for this view using the
-given el. el can be a CSS selector or an HTML string, a jQuery
-context or an element. Subclasses can override this to utilize an
-alternative DOM manipulation API and are only required to set the
-this.el property.
+ Set callbacks, where this.events is a hash of
+{“event selector”: “callback”}
+{
+ 'mousedown .title': 'edit',
+ 'click .button': 'save',
+ 'click .open': function(e) { ... }
+}
+
pairs. Callbacks will be bound to the view, with this set properly.
+Uses event delegation for efficiency.
+Omitting the selector binds the event to this.el.
- _setElement: function(el) {
- this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
- this.el = this.$el[0];
+ delegateEvents: function(events) {
+ events || (events = _.result(this, 'events'));
+ if (!events) return this;
+ this.undelegateEvents();
+ for (var key in events) {
+ var method = events[key];
+ if (!_.isFunction(method)) method = this[method];
+ if (!method) continue;
+ var match = key.match(delegateEventSplitter);
+ this.delegate(match[1], match[2], _.bind(method, this));
+ }
+ return this;
},
@@ -3228,29 +3298,14 @@ alternative DOM manipulation API and are only required to set the
- Set callbacks, where this.events is a hash of
-{“event selector”: “callback”}
-{
- 'mousedown .title': 'edit',
- 'click .button': 'save',
- 'click .open': function(e) { ... }
-}
-
pairs. Callbacks will be bound to the view, with this set properly.
-Uses event delegation for efficiency.
-Omitting the selector binds the event to this.el.
+ Add a single event listener to the view’s element (or a child element
+using selector). This only works for delegate-able events: not focus,
+blur, and not change, submit, and reset in Internet Explorer.
- delegateEvents: function(events) {
- if (!(events || (events = _.result(this, 'events')))) return this;
- this.undelegateEvents();
- for (var key in events) {
- var method = events[key];
- if (!_.isFunction(method)) method = this[events[key]];
- if (!method) continue;
- var match = key.match(delegateEventSplitter);
- this.delegate(match[1], match[2], _.bind(method, this));
- }
+ delegate: function(eventName, selector, listener) {
+ this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
return this;
},
@@ -3263,14 +3318,15 @@ Omitting the selector binds the event to this.el.
- Add a single event listener to the view’s element (or a child element
-using selector). This only works for delegate-able events: not focus,
-blur, and not change, submit, and reset in Internet Explorer.
+ Clears all callbacks previously bound to the view by delegateEvents.
+You usually don’t need to use this, but may wish to if you have multiple
+Backbone views attached to the same DOM element.
- delegate: function(eventName, selector, listener) {
- this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
+ undelegateEvents: function() {
+ if (this.$el) this.$el.off('.delegateEvents' + this.cid);
+ return this;
},
@@ -3282,14 +3338,13 @@ using selector). This only works for delegate-able events: not
¶
- Clears all callbacks previously bound to the view by delegateEvents.
-You usually don’t need to use this, but may wish to if you have multiple
-Backbone views attached to the same DOM element.
+ A finer-grained undelegateEvents for removing a single delegated event.
+selector and listener are both optional.
- undelegateEvents: function() {
- if (this.$el) this.$el.off('.delegateEvents' + this.cid);
+ undelegate: function(eventName, selector, listener) {
+ this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
return this;
},
@@ -3302,13 +3357,13 @@ Backbone views attached to the same DOM element.
- A finer-grained undelegateEvents for removing a single delegated event.
-selector and listener are both optional.
+ Produces a DOM element to be assigned to your view. Exposed for
+subclasses using an alternative DOM manipulation API.
- undelegate: function(eventName, selector, listener) {
- this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
+ _createElement: function(tagName) {
+ return document.createElement(tagName);
},
@@ -3320,24 +3375,6 @@ Backbone views attached to the same DOM element.
- Produces a DOM element to be assigned to your view. Exposed for
-subclasses using an alternative DOM manipulation API.
-
-
-
- _createElement: function(tagName) {
- return document.createElement(tagName);
- },
-
-
-
-
-
-
-
-
- ¶
-
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
@@ -3345,7 +3382,7 @@ an element from the id, className and tagName
- _ensureElement: function() {
+ _ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
@@ -3360,18 +3397,18 @@ an element from the id, className and tagName
-
+
Set attributes from a hash on this view’s element. Exposed for
subclasses using an alternative DOM manipulation API.
- _setAttributes: function(attributes) {
+ _setAttributes: function(attributes) {
this.$el.attr(attributes);
}
@@ -3380,14 +3417,26 @@ subclasses using an alternative DOM manipulation API.
+
+
+
+
+ ¶
+
+ Backbone.sync
+
+
+
+
+
+
- Backbone.sync
-
+
@@ -3399,18 +3448,6 @@ subclasses using an alternative DOM manipulation API.
-
-
-
-
-
-
-
-
-
-
- ¶
-
Override this function to change the manner in which Backbone persists
models to the server. You will be passed the type of request, and the
model in question. By default, makes a RESTful Ajax request
@@ -3429,17 +3466,17 @@ it difficult to read the body of PUT requests.
- Backbone.sync = function(method, model, options) {
+ Backbone.sync = function(method, model, options) {
var type = methodMap[method];
-
+
Default options, unless specified.
@@ -3453,11 +3490,11 @@ it difficult to read the body of PUT requests.
-
+
Default JSON-request options.
@@ -3468,11 +3505,11 @@ it difficult to read the body of PUT requests.
-
+
Ensure that we have a URL.
@@ -3485,11 +3522,11 @@ it difficult to read the body of PUT requests.
-
+
Ensure that we have the appropriate request data.
@@ -3503,11 +3540,11 @@ it difficult to read the body of PUT requests.
-
+
For older servers, emulate JSON by encoding the request into an HTML-form.
@@ -3521,11 +3558,11 @@ it difficult to read the body of PUT requests.
-
+
For older servers, emulate HTTP by mimicking the HTTP method with _method
And an X-HTTP-Method-Override header.
@@ -3536,7 +3573,7 @@ And an X-HTTP-Method-Override header.
params.type = 'POST';
if (options.emulateJSON) params.data._method = type;
var beforeSend = options.beforeSend;
- options.beforeSend = function(xhr) {
+ options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
if (beforeSend) return beforeSend.apply(this, arguments);
};
@@ -3545,11 +3582,11 @@ And an X-HTTP-Method-Override header.
-
+
Don’t process data on a non-GET request.
@@ -3562,18 +3599,18 @@ And an X-HTTP-Method-Override header.
-
+
var error = options.error;
- options.error = function(xhr, textStatus, errorThrown) {
+ options.error = function(xhr, textStatus, errorThrown) {
options.textStatus = textStatus;
options.errorThrown = errorThrown;
if (error) error.call(options.context, xhr, textStatus, errorThrown);
@@ -3582,11 +3619,11 @@ And an X-HTTP-Method-Override header.
-
+
Make the request, allowing the user to override any Ajax options.
@@ -3600,11 +3637,11 @@ And an X-HTTP-Method-Override header.
-
+
Map from CRUD to HTTP for our default Backbone.sync implementation.
@@ -3613,9 +3650,27 @@ And an X-HTTP-Method-Override header.
var methodMap = {
'create': 'POST',
'update': 'PUT',
- 'patch': 'PATCH',
+ 'patch': 'PATCH',
'delete': 'DELETE',
- 'read': 'GET'
+ 'read': 'GET'
+ };
+
+
+
+
+
+
+
+
+ ¶
+
+ Set the default implementation of Backbone.ajax to proxy through to $.
+Override this if you’d like to use a different library.
+
+
+
+ Backbone.ajax = function() {
+ return Backbone.$.ajax.apply(Backbone.$, arguments);
};
@@ -3627,15 +3682,10 @@ And an X-HTTP-Method-Override header.
- Set the default implementation of Backbone.ajax to proxy through to $.
-Override this if you’d like to use a different library.
+ Backbone.Router
- Backbone.ajax = function() {
- return Backbone.$.ajax.apply(Backbone.$, arguments);
- };
-
@@ -3645,8 +3695,7 @@ Override this if you’d like to use a different library.
- Backbone.Router
-
+
@@ -3658,24 +3707,12 @@ Override this if you’d like to use a different library.
-
-
-
-
-
-
-
-
-
-
- ¶
-
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.
- var Router = Backbone.Router = function(options) {
+ var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
@@ -3685,11 +3722,11 @@ matched. Creating a new one sets its routes hash, if not set static
-
+
Cached regular expressions for matching named param parts and splatted
parts of route strings.
@@ -3704,11 +3741,11 @@ parts of route strings.
-
+
Set up all inheritable Backbone.Router properties and methods.
@@ -3719,36 +3756,36 @@ parts of route strings.
-
+
- initialize: function(){},
+ initialize: function(){},
-
+
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) {
...
});
- route: function(route, name, callback) {
+ route: function(route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (_.isFunction(name)) {
callback = name;
@@ -3756,7 +3793,7 @@ initialization logic.
}
if (!callback) callback = this[name];
var router = this;
- Backbone.history.route(route, function(fragment) {
+ Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
if (router.execute(callback, args, name) !== false) {
router.trigger.apply(router, ['route:' + name].concat(args));
@@ -3770,55 +3807,55 @@ initialization logic.
-
+
Execute a route handler with the provided parameters. This is an
excellent place to do pre-route setup or post-route cleanup.
- execute: function(callback, args, name) {
+ execute: function(callback, args, name) {
if (callback) callback.apply(this, args);
},
+
+
+
+
+ ¶
+
+ Simple proxy to Backbone.history to save a fragment into the history.
+
+
+
+ navigate: function(fragment, options) {
+ Backbone.history.navigate(fragment, options);
+ return this;
+ },
+
+
+
+
- Simple proxy to Backbone.history to save a fragment into the history.
-
-
-
- navigate: function(fragment, options) {
- Backbone.history.navigate(fragment, options);
- return this;
- },
-
-
-
-
-
-
-
-
- ¶
-
Bind all defined routes to Backbone.history. We have to reverse the
order of the routes here to support behavior where the most general
routes can be defined at the bottom of the route map.
- _bindRoutes: function() {
+ _bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = _.keys(this.routes);
@@ -3830,21 +3867,21 @@ routes can be defined at the bottom of the route map.
-
+
Convert a route string into a regular expression, suitable for matching
against the current location hash.
- _routeToRegExp: function(route) {
+ _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, '([^?]*?)');
@@ -3854,11 +3891,11 @@ against the current location hash.
-
+
Given a route, and a URL fragment that it matches, return the array of
extracted decoded parameters. Empty or unmatched parameters will be
@@ -3866,18 +3903,18 @@ treated as null to normalize cross-browser behavior.
- _extractParameters: function(route, fragment) {
+ _extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
- return _.map(params, function(param, i) {
+ return _.map(params, function(param, i) {
-
+
Don’t decode the search params.
@@ -3893,14 +3930,26 @@ treated as null to normalize cross-browser behavior.
+
+
+
+
+ ¶
+
+ Backbone.History
+
+
+
+
+
+
- Backbone.History
-
+
@@ -3912,9 +3961,18 @@ treated as null to normalize cross-browser behavior.
-
+ Handles cross-browser history management, based on either
+pushState and real URLs, or
+onhashchange
+and URL fragments. If the browser supports neither (old IE, natch),
+falls back to polling.
+
+ var History = Backbone.History = function() {
+ this.handlers = [];
+ this.checkUrl = _.bind(this.checkUrl, this);
+
@@ -3924,27 +3982,6 @@ treated as null to normalize cross-browser behavior.
- Handles cross-browser history management, based on either
-pushState and real URLs, or
-onhashchange
-and URL fragments. If the browser supports neither (old IE, natch),
-falls back to polling.
-
-
-
- var History = Backbone.History = function() {
- this.handlers = [];
- _.bindAll(this, 'checkUrl');
-
-
-
-
-
-
-
-
- ¶
-
Ensure that History can be used outside of the browser.
@@ -3958,11 +3995,11 @@ falls back to polling.
-
+
Cached regex for stripping a leading hash/slash and trailing space.
@@ -3973,11 +4010,11 @@ falls back to polling.
-
+
Cached regex for stripping leading and trailing slashes.
@@ -3988,11 +4025,11 @@ falls back to polling.
-
+
Cached regex for stripping urls of hash.
@@ -4003,11 +4040,11 @@ falls back to polling.
-
+
Has the history handling already been started?
@@ -4018,11 +4055,11 @@ falls back to polling.
-
+
Set up all inheritable Backbone.History properties and methods.
@@ -4033,11 +4070,11 @@ falls back to polling.
-
+
The default interval to poll for hash changes, if necessary, is
twenty times a second.
@@ -4049,19 +4086,38 @@ twenty times a second.
+
+
+
+
+ ¶
+
+ Are we at the app root?
+
+
+
+ atRoot: function() {
+ var path = this.location.pathname.replace(/[^\/]$/, '$&/');
+ return path === this.root && !this.getSearch();
+ },
+
+
+
+
- atRoot: function() {
- var path = this.location.pathname.replace(/[^\/]$/, '$&/');
- return path === this.root && !this.getSearch();
+ matchRoot: function() {
+ var path = this.decodeFragment(this.location.pathname);
+ var rootPath = path.slice(0, this.root.length - 1) + '/';
+ return rootPath === this.root;
},
@@ -4073,14 +4129,14 @@ twenty times a second.
- Does the pathname match the root?
+ Unicode characters in location.pathname are percent encoded so they’re
+decoded for comparison. %25 should not be decoded since it may be part
+of an encoded parameter.
- matchRoot: function() {
- var path = this.decodeFragment(this.location.pathname);
- var root = path.slice(0, this.root.length - 1) + '/';
- return root === this.root;
+ decodeFragment: function(fragment) {
+ return decodeURI(fragment.replace(/%25/g, '%2525'));
},
@@ -4092,14 +4148,14 @@ twenty times a second.
- Unicode characters in location.pathname are percent encoded so they’re
-decoded for comparison. %25 should not be decoded since it may be part
-of an encoded parameter.
+ In IE6, the hash fragment and search params are incorrect if the
+fragment contains ?.
- decodeFragment: function(fragment) {
- return decodeURI(fragment.replace(/%25/g, '%2525'));
+ getSearch: function() {
+ var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
+ return match ? match[0] : '';
},
@@ -4111,14 +4167,14 @@ of an encoded parameter.
- In IE6, the hash fragment and search params are incorrect if the
-fragment contains ?.
+ Gets the true hash value. Cannot use location.hash directly due to bug
+in Firefox where location.hash will always be decoded.
- getSearch: function() {
- var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
- return match ? match[0] : '';
+ getHash: function(window) {
+ var match = (window || this).location.href.match(/#(.*)$/);
+ return match ? match[1] : '';
},
@@ -4130,14 +4186,15 @@ fragment contains ?.
- Gets the true hash value. Cannot use location.hash directly due to bug
-in Firefox where location.hash will always be decoded.
+ Get the pathname and search params, without the root.
- getHash: function(window) {
- var match = (window || this).location.href.match(/#(.*)$/);
- return match ? match[1] : '';
+ getPath: function() {
+ var path = this.decodeFragment(
+ this.location.pathname + this.getSearch()
+ ).slice(this.root.length - 1);
+ return path.charAt(0) === '/' ? path.slice(1) : path;
},
@@ -4149,31 +4206,11 @@ in Firefox where location.hash will always be decoded.
- Get the pathname and search params, without the root.
-
-
-
- getPath: function() {
- var path = this.decodeFragment(
- this.location.pathname + this.getSearch()
- ).slice(this.root.length - 1);
- return path.charAt(0) === '/' ? path.slice(1) : path;
- },
-
-
-
-
-
-
-
-
- ¶
-
Get the cross-browser normalized URL fragment from the path or hash.
- getFragment: function(fragment) {
+ getFragment: function(fragment) {
if (fragment == null) {
if (this._usePushState || !this._wantsHashChange) {
fragment = this.getPath();
@@ -4187,54 +4224,54 @@ in Firefox where location.hash will always be decoded.
-
+
Start the hash change handling, returning true if the current URL matches
an existing route, and false otherwise.
- start: function(options) {
+ start: function(options) {
if (History.started) throw new Error('Backbone.history has already been started');
History.started = true;
+
+
+
+
+ ¶
+
+ Figure out the initial configuration. Do we need an iframe?
+Is pushState desired … is it available?
+
+
+
+ this.options = _.extend({root: '/'}, this.options, options);
+ this.root = this.options.root;
+ this._wantsHashChange = this.options.hashChange !== false;
+ this._hasHashChange = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
+ this._useHashChange = this._wantsHashChange && this._hasHashChange;
+ this._wantsPushState = !!this.options.pushState;
+ this._hasPushState = !!(this.history && this.history.pushState);
+ this._usePushState = this._wantsPushState && this._hasPushState;
+ this.fragment = this.getFragment();
+
+
+
+
- Figure out the initial configuration. Do we need an iframe?
-Is pushState desired … is it available?
-
-
-
- this.options = _.extend({root: '/'}, this.options, options);
- this.root = this.options.root;
- this._wantsHashChange = this.options.hashChange !== false;
- this._hasHashChange = 'onhashchange' in window;
- this._useHashChange = this._wantsHashChange && this._hasHashChange;
- this._wantsPushState = !!this.options.pushState;
- this._hasPushState = !!(this.history && this.history.pushState);
- this._usePushState = this._wantsPushState && this._hasPushState;
- this.fragment = this.getFragment();
-
-
-
-
-
-
-
-
- ¶
-
Normalize root to always include a leading and trailing slash.
@@ -4244,11 +4281,11 @@ Is pushState desired … is it available?
-
+
Transition from hashChange to pushState or vice versa if both are
requested.
@@ -4260,11 +4297,11 @@ requested.
-
+
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…
@@ -4272,17 +4309,17 @@ browser, but we’re currently in a browser that doesn’t support it…
if (!this._hasPushState && !this.atRoot()) {
- var root = this.root.slice(0, -1) || '/';
- this.location.replace(root + '#' + this.getPath());
+ var rootPath = this.root.slice(0, -1) || '/';
+ this.location.replace(rootPath + '#' + this.getPath());
-
+
Return immediately as browser will do redirect to new url
@@ -4293,11 +4330,11 @@ browser, but we’re currently in a browser that doesn’t support it…
-
+
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…
@@ -4313,11 +4350,11 @@ in a browser where it could be pushState-based instead…
-
+
Proxy an iframe to handle location events if the browser doesn’t
support the hashchange event, HTML5 history, or the user wants
@@ -4326,29 +4363,47 @@ support the hashchange event, HTML5 history, or the user wants
if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
- var iframe = document.createElement('iframe');
- iframe.src = 'javascript:0';
- iframe.style.display = 'none';
- iframe.tabIndex = -1;
+ this.iframe = document.createElement('iframe');
+ this.iframe.src = 'javascript:0';
+ this.iframe.style.display = 'none';
+ this.iframe.tabIndex = -1;
var body = document.body;
+
+
+
+
+ ¶
+
+ Using appendChild will throw on IE < 9 if the document is not ready.
+
+
+
+ var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
+ iWindow.document.open();
+ iWindow.document.close();
+ iWindow.location.hash = '#' + this.fragment;
+ }
+
+
+
+
- Using appendChild will throw on IE < 9 if the document is not ready.
+ Add a cross-platform addEventListener shim for older browsers.
- this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow;
- this.iframe.document.open().close();
- this.iframe.location.hash = '#' + this.fragment;
- }
+ var addEventListener = window.addEventListener || function(eventName, listener) {
+ return attachEvent('on' + eventName, listener);
+ };
@@ -4359,23 +4414,6 @@ support the hashchange event, HTML5 history, or the user wants
- Add a cross-platform addEventListener shim for older browsers.
-
-
-
- var addEventListener = window.addEventListener || function (eventName, listener) {
- return attachEvent('on' + eventName, listener);
- };
-
-
-
-
-
-
-
-
- ¶
-
Depending on whether we’re using pushState or hashes, and whether
‘onhashchange’ is supported, determine how we check the URL state.
@@ -4395,18 +4433,35 @@ support the hashchange event, HTML5 history, or the user wants
-
+
Disable Backbone.history, perhaps temporarily. Not useful in a real app,
but possibly useful for unit testing Routers.
- stop: function() {
+ stop: function() {
+
+
+
+
+
+
+
+
+ ¶
+
+ Add a cross-platform removeEventListener shim for older browsers.
+
+
+
+ var removeEventListener = window.removeEventListener || function(eventName, listener) {
+ return detachEvent('on' + eventName, listener);
+ };
@@ -4417,23 +4472,6 @@ but possibly useful for unit testing Routers.
- Add a cross-platform removeEventListener shim for older browsers.
-
-
-
- var removeEventListener = window.removeEventListener || function (eventName, listener) {
- return detachEvent('on' + eventName, listener);
- };
-
-
-
-
-
-
-
-
- ¶
-
Remove window listeners.
@@ -4447,29 +4485,29 @@ but possibly useful for unit testing Routers.
-
+
if (this.iframe) {
- document.body.removeChild(this.iframe.frameElement);
+ document.body.removeChild(this.iframe);
this.iframe = null;
}
-
+
Some environments will throw when clearing an undefined interval.
@@ -4482,54 +4520,54 @@ but possibly useful for unit testing Routers.
-
+
Add a route to be tested when the fragment changes. Routes added later
may override previous routes.
- route: function(route, callback) {
+ route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
+
+
+
+
+ ¶
+
+ Checks the current URL to see if it has changed, and if it has,
+calls loadUrl, normalizing across the hidden iframe.
+
+
+
+ checkUrl: function(e) {
+ var current = this.getFragment();
+
+
+
+
- Checks the current URL to see if it has changed, and if it has,
-calls loadUrl, normalizing across the hidden iframe.
-
-
-
- checkUrl: function(e) {
- var current = this.getFragment();
-
-
-
-
-
-
-
-
- ¶
-
If the user pressed the back button, the iframe’s hash will have
changed and we should use that for comparison.
if (current === this.fragment && this.iframe) {
- current = this.getHash(this.iframe);
+ current = this.getHash(this.iframe.contentWindow);
}
if (current === this.fragment) return false;
@@ -4540,11 +4578,11 @@ changed and we should use that for comparison.
-
+
Attempt to load the current URL fragment. If a route succeeds with a
match, returns true. If no defined routes matches the fragment,
@@ -4552,16 +4590,16 @@ returns false.
- loadUrl: function(fragment) {
+ loadUrl: function(fragment) {
-
+
If the root doesn’t match, no routes can match either.
@@ -4569,7 +4607,7 @@ returns false.
if (!this.matchRoot()) return false;
fragment = this.fragment = this.getFragment(fragment);
- return _.any(this.handlers, function(handler) {
+ return _.some(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
@@ -4580,11 +4618,11 @@ returns false.
-
+
Save a fragment into the hash history, or replace the URL state if the
‘replace’ option is passed. You are responsible for properly URL-encoding
@@ -4595,18 +4633,18 @@ 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 (!options || options === true) options = {trigger: !!options};
-
+
Normalize the fragment.
@@ -4617,30 +4655,30 @@ you wish to modify the current URL without adding an entry to the history.
-
+
- var root = this.root;
+ var rootPath = this.root;
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 hash and decode for matching.
@@ -4654,11 +4692,11 @@ you wish to modify the current URL without adding an entry to the history.
-
+
If pushState is available, we use it to set the fragment as a real URL.
@@ -4670,11 +4708,11 @@ you wish to modify the current URL without adding an entry to the history.
-
+
If hash changes haven’t been explicitly disabled, update the hash
fragment to store history.
@@ -4683,7 +4721,31 @@ fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
- if (this.iframe && (fragment !== this.getHash(this.iframe))) {
+ if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
+ var iWindow = this.iframe.contentWindow;
+
+
+
+
+
+
+
+
+ ¶
+
+ Opening and closing the iframe tricks IE7 and earlier to push a
+history entry on hash-tag change. When replace is true, we don’t
+want this.
+
+
+
+ if (!options.replace) {
+ iWindow.document.open();
+ iWindow.document.close();
+ }
+
+ this._updateHash(iWindow.location, fragment, options.replace);
+ }
@@ -4694,25 +4756,6 @@ fragment to store history.
- Opening and closing the iframe tricks IE7 and earlier to push a
-history entry on hash-tag change. When replace is true, we don’t
-want this.
-
-
-
- if (!options.replace) this.iframe.document.open().close();
- this._updateHash(this.iframe.location, fragment, options.replace);
- }
-
-
-
-
-
-
-
-
- ¶
-
If you’ve told us that you explicitly don’t want fallback hashchange-
based history, then navigate becomes a page refresh.
@@ -4727,18 +4770,18 @@ based history, then navigate becomes a page refresh.
-
+
Update the hash location, either replacing the current entry, or adding
a new one to the browser history.
- _updateHash: function(location, fragment, replace) {
+ _updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
@@ -4747,11 +4790,11 @@ a new one to the browser history.
-
+
Some browsers require that hash contains a leading #.
@@ -4766,11 +4809,11 @@ a new one to the browser history.
-
+
Create the default Backbone.history.
@@ -4781,14 +4824,26 @@ a new one to the browser history.
+
+
+
+
+ ¶
+
+ Helpers
+
+
+
+
+
+
- Helpers
-
+
@@ -4800,9 +4855,16 @@ a new one to the browser history.
-
+ Helper function to correctly set up the prototype chain for subclasses.
+Similar to goog.inherits, but uses a hash of prototype properties and
+class properties to be extended.
+
+ var extend = function(protoProps, staticProps) {
+ var parent = this;
+ var child;
+
@@ -4812,15 +4874,17 @@ a new one to the browser history.
- Helper function to correctly set up the prototype chain for subclasses.
-Similar to goog.inherits, but uses a hash of prototype properties and
-class properties to be extended.
+ The constructor function for the new subclass is either defined by you
+(the “constructor” property in your extend definition), or defaulted
+by us to simply call the parent constructor.
- var extend = function(protoProps, staticProps) {
- var parent = this;
- var child;
+ if (protoProps && _.has(protoProps, 'constructor')) {
+ child = protoProps.constructor;
+ } else {
+ child = function(){ return parent.apply(this, arguments); };
+ }
@@ -4831,17 +4895,11 @@ class properties to be extended.
- The constructor function for the new subclass is either defined by you
-(the “constructor” property in your extend definition), or defaulted
-by us to simply call the parent constructor.
+ Add static properties to the constructor function, if supplied.
- if (protoProps && _.has(protoProps, 'constructor')) {
- child = protoProps.constructor;
- } else {
- child = function(){ return parent.apply(this, arguments); };
- }
+ _.extend(child, parent, staticProps);
@@ -4852,11 +4910,13 @@ by us to simply call the parent constructor.
- Add static properties to the constructor function, if supplied.
+ Set the prototype chain to inherit from parent, without calling
+parent‘s constructor function and add the prototype properties.
- _.extend(child, parent, staticProps);
+ child.prototype = _.create(parent.prototype, protoProps);
+ child.prototype.constructor = child;
@@ -4867,40 +4927,6 @@ by us to simply call the parent constructor.
- Set the prototype chain to inherit from parent, without calling
-parent constructor function.
-
-
-
- var Surrogate = function(){ this.constructor = child; };
- Surrogate.prototype = parent.prototype;
- child.prototype = new Surrogate;
-
-
-
-
-
-
-
-
- ¶
-
- Add prototype properties (instance properties) to the subclass,
-if supplied.
-
-
-
- if (protoProps) _.extend(child.prototype, protoProps);
-
-
-
-
-
-
-
-
- ¶
-
Set a convenience property in case the parent’s prototype is needed
later.
@@ -4914,11 +4940,11 @@ later.
-
+
Set up inheritance for the model, collection, router, view and history.
@@ -4929,44 +4955,43 @@ later.
-
+
- var urlError = function() {
+ var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
-
+
- var wrapError = function(model, options) {
+ var wrapError = function(model, options) {
var error = options.error;
- options.error = function(resp) {
+ options.error = function(resp) {
if (error) error.call(options.context, model, resp, options);
model.trigger('error', model, resp, options);
};
};
return Backbone;
-
-}));
+});
diff --git a/docs/backbone.localStorage.html b/docs/backbone.localStorage.html
index b4bd2bd1..42c42c46 100644
--- a/docs/backbone.localStorage.html
+++ b/docs/backbone.localStorage.html
@@ -59,7 +59,7 @@
*
* https://github.com/jeromegn/Backbone.localStorage
*/
-(function (root, factory) {
+(function (root, factory) {
if (typeof define === "function" && define.amd) {
@@ -75,7 +75,7 @@
- define(["underscore","backbone"], function(_, Backbone) {
+ define(["underscore","backbone"], function(_, Backbone) {
@@ -109,7 +109,7 @@
factory(_, Backbone);
}
-}(this, function(_, Backbone) {
+}(this, function(_, Backbone) {
@@ -153,7 +153,7 @@ to make things work even if they are removed from the global namespace
- function S4() {
+ function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
@@ -170,7 +170,7 @@ to make things work even if they are removed from the global namespace
- function guid() {
+ function guid() {
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
@@ -185,11 +185,11 @@ to make things work even if they are removed from the global namespace
Our Store is represented by a single JS object in localStorage. Create it
with a meaningful name, like the name you’d give a table.
-window.Store is deprectated, use Backbone.LocalStorage instead
+window.Store is deprecated, use Backbone.LocalStorage instead
- Backbone.LocalStorage = window.Store = function(name) {
+ Backbone.LocalStorage = window.Store = function(name) {
this.name = name;
var store = this.localStorage().getItem(this.name);
this.records = (store && store.split(",")) || [];
@@ -210,7 +210,7 @@ _.extend(Backbone.LocalStorage.prototype, {
- save: function() {
+ save: function() {
this.localStorage().setItem(this.name, this.records.join(","));
},
@@ -228,7 +228,7 @@ have an id of it’s own.
- create: function(model) {
+ create: function(model) {
if (!model.id) {
model.id = guid();
model.set(model.idAttribute, model.id);
@@ -252,7 +252,7 @@ have an id of it’s own.
- update: function(model) {
+ update: function(model) {
this.localStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
if (!_.include(this.records, model.id.toString()))
this.records.push(model.id.toString()); this.save();
@@ -272,7 +272,7 @@ have an id of it’s own.
- find: function(model) {
+ find: function(model) {
return this.jsonData(this.localStorage().getItem(this.name+"-"+model.id));
},
@@ -289,9 +289,9 @@ have an id of it’s own.
- findAll: function() {
+ findAll: function() {
return _(this.records).chain()
- .map(function(id){
+ .map(function(id){
return this.jsonData(this.localStorage().getItem(this.name+"-"+id));
}, this)
.compact()
@@ -311,18 +311,18 @@ have an id of it’s own.
- destroy: function(model) {
+ destroy: function(model) {
if (model.isNew())
return false
this.localStorage().removeItem(this.name+"-"+model.id);
- this.records = _.reject(this.records, function(id){
+ this.records = _.reject(this.records, function(id){
return id === model.id.toString();
});
this.save();
return model;
},
- localStorage: function() {
+ localStorage: function() {
return localStorage;
},
@@ -339,7 +339,7 @@ have an id of it’s own.
- jsonData: function (data) {
+ jsonData: function (data) {
return data && JSON.parse(data);
}
@@ -360,7 +360,7 @@ window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStora
- Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
+ Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync =