Daniel@0
|
1 // Backbone.js 1.1.2
|
Daniel@0
|
2
|
Daniel@0
|
3 // (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
Daniel@0
|
4 // Backbone may be freely distributed under the MIT license.
|
Daniel@0
|
5 // For all details and documentation:
|
Daniel@0
|
6 // http://backbonejs.org
|
Daniel@0
|
7
|
Daniel@0
|
8 (function(root, factory) {
|
Daniel@0
|
9
|
Daniel@0
|
10 // Set up Backbone appropriately for the environment. Start with AMD.
|
Daniel@0
|
11 if (typeof define === 'function' && define.amd) {
|
Daniel@0
|
12 define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
|
Daniel@0
|
13 // Export global even in AMD case in case this script is loaded with
|
Daniel@0
|
14 // others that may still expect a global Backbone.
|
Daniel@0
|
15 root.Backbone = factory(root, exports, _, $);
|
Daniel@0
|
16 });
|
Daniel@0
|
17
|
Daniel@0
|
18 // Next for Node.js or CommonJS. jQuery may not be needed as a module.
|
Daniel@0
|
19 } else if (typeof exports !== 'undefined') {
|
Daniel@0
|
20 var _ = require('underscore');
|
Daniel@0
|
21 factory(root, exports, _);
|
Daniel@0
|
22
|
Daniel@0
|
23 // Finally, as a browser global.
|
Daniel@0
|
24 } else {
|
Daniel@0
|
25 root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
|
Daniel@0
|
26 }
|
Daniel@0
|
27
|
Daniel@0
|
28 }(this, function(root, Backbone, _, $) {
|
Daniel@0
|
29
|
Daniel@0
|
30 // Initial Setup
|
Daniel@0
|
31 // -------------
|
Daniel@0
|
32
|
Daniel@0
|
33 // Save the previous value of the `Backbone` variable, so that it can be
|
Daniel@0
|
34 // restored later on, if `noConflict` is used.
|
Daniel@0
|
35 var previousBackbone = root.Backbone;
|
Daniel@0
|
36
|
Daniel@0
|
37 // Create local references to array methods we'll want to use later.
|
Daniel@0
|
38 var array = [];
|
Daniel@0
|
39 var push = array.push;
|
Daniel@0
|
40 var slice = array.slice;
|
Daniel@0
|
41 var splice = array.splice;
|
Daniel@0
|
42
|
Daniel@0
|
43 // Current version of the library. Keep in sync with `package.json`.
|
Daniel@0
|
44 Backbone.VERSION = '1.1.2';
|
Daniel@0
|
45
|
Daniel@0
|
46 // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
|
Daniel@0
|
47 // the `$` variable.
|
Daniel@0
|
48 Backbone.$ = $;
|
Daniel@0
|
49
|
Daniel@0
|
50 // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
|
Daniel@0
|
51 // to its previous owner. Returns a reference to this Backbone object.
|
Daniel@0
|
52 Backbone.noConflict = function() {
|
Daniel@0
|
53 root.Backbone = previousBackbone;
|
Daniel@0
|
54 return this;
|
Daniel@0
|
55 };
|
Daniel@0
|
56
|
Daniel@0
|
57 // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
|
Daniel@0
|
58 // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
|
Daniel@0
|
59 // set a `X-Http-Method-Override` header.
|
Daniel@0
|
60 Backbone.emulateHTTP = false;
|
Daniel@0
|
61
|
Daniel@0
|
62 // Turn on `emulateJSON` to support legacy servers that can't deal with direct
|
Daniel@0
|
63 // `application/json` requests ... will encode the body as
|
Daniel@0
|
64 // `application/x-www-form-urlencoded` instead and will send the model in a
|
Daniel@0
|
65 // form param named `model`.
|
Daniel@0
|
66 Backbone.emulateJSON = false;
|
Daniel@0
|
67
|
Daniel@0
|
68 // Backbone.Events
|
Daniel@0
|
69 // ---------------
|
Daniel@0
|
70
|
Daniel@0
|
71 // A module that can be mixed in to *any object* in order to provide it with
|
Daniel@0
|
72 // custom events. You may bind with `on` or remove with `off` callback
|
Daniel@0
|
73 // functions to an event; `trigger`-ing an event fires all callbacks in
|
Daniel@0
|
74 // succession.
|
Daniel@0
|
75 //
|
Daniel@0
|
76 // var object = {};
|
Daniel@0
|
77 // _.extend(object, Backbone.Events);
|
Daniel@0
|
78 // object.on('expand', function(){ alert('expanded'); });
|
Daniel@0
|
79 // object.trigger('expand');
|
Daniel@0
|
80 //
|
Daniel@0
|
81 var Events = Backbone.Events = {
|
Daniel@0
|
82
|
Daniel@0
|
83 // Bind an event to a `callback` function. Passing `"all"` will bind
|
Daniel@0
|
84 // the callback to all events fired.
|
Daniel@0
|
85 on: function(name, callback, context) {
|
Daniel@0
|
86 if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
|
Daniel@0
|
87 this._events || (this._events = {});
|
Daniel@0
|
88 var events = this._events[name] || (this._events[name] = []);
|
Daniel@0
|
89 events.push({callback: callback, context: context, ctx: context || this});
|
Daniel@0
|
90 return this;
|
Daniel@0
|
91 },
|
Daniel@0
|
92
|
Daniel@0
|
93 // Bind an event to only be triggered a single time. After the first time
|
Daniel@0
|
94 // the callback is invoked, it will be removed.
|
Daniel@0
|
95 once: function(name, callback, context) {
|
Daniel@0
|
96 if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
|
Daniel@0
|
97 var self = this;
|
Daniel@0
|
98 var once = _.once(function() {
|
Daniel@0
|
99 self.off(name, once);
|
Daniel@0
|
100 callback.apply(this, arguments);
|
Daniel@0
|
101 });
|
Daniel@0
|
102 once._callback = callback;
|
Daniel@0
|
103 return this.on(name, once, context);
|
Daniel@0
|
104 },
|
Daniel@0
|
105
|
Daniel@0
|
106 // Remove one or many callbacks. If `context` is null, removes all
|
Daniel@0
|
107 // callbacks with that function. If `callback` is null, removes all
|
Daniel@0
|
108 // callbacks for the event. If `name` is null, removes all bound
|
Daniel@0
|
109 // callbacks for all events.
|
Daniel@0
|
110 off: function(name, callback, context) {
|
Daniel@0
|
111 var retain, ev, events, names, i, l, j, k;
|
Daniel@0
|
112 if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
|
Daniel@0
|
113 if (!name && !callback && !context) {
|
Daniel@0
|
114 this._events = void 0;
|
Daniel@0
|
115 return this;
|
Daniel@0
|
116 }
|
Daniel@0
|
117 names = name ? [name] : _.keys(this._events);
|
Daniel@0
|
118 for (i = 0, l = names.length; i < l; i++) {
|
Daniel@0
|
119 name = names[i];
|
Daniel@0
|
120 if (events = this._events[name]) {
|
Daniel@0
|
121 this._events[name] = retain = [];
|
Daniel@0
|
122 if (callback || context) {
|
Daniel@0
|
123 for (j = 0, k = events.length; j < k; j++) {
|
Daniel@0
|
124 ev = events[j];
|
Daniel@0
|
125 if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
|
Daniel@0
|
126 (context && context !== ev.context)) {
|
Daniel@0
|
127 retain.push(ev);
|
Daniel@0
|
128 }
|
Daniel@0
|
129 }
|
Daniel@0
|
130 }
|
Daniel@0
|
131 if (!retain.length) delete this._events[name];
|
Daniel@0
|
132 }
|
Daniel@0
|
133 }
|
Daniel@0
|
134
|
Daniel@0
|
135 return this;
|
Daniel@0
|
136 },
|
Daniel@0
|
137
|
Daniel@0
|
138 // Trigger one or many events, firing all bound callbacks. Callbacks are
|
Daniel@0
|
139 // passed the same arguments as `trigger` is, apart from the event name
|
Daniel@0
|
140 // (unless you're listening on `"all"`, which will cause your callback to
|
Daniel@0
|
141 // receive the true name of the event as the first argument).
|
Daniel@0
|
142 trigger: function(name) {
|
Daniel@0
|
143 if (!this._events) return this;
|
Daniel@0
|
144 var args = slice.call(arguments, 1);
|
Daniel@0
|
145 if (!eventsApi(this, 'trigger', name, args)) return this;
|
Daniel@0
|
146 var events = this._events[name];
|
Daniel@0
|
147 var allEvents = this._events.all;
|
Daniel@0
|
148 if (events) triggerEvents(events, args);
|
Daniel@0
|
149 if (allEvents) triggerEvents(allEvents, arguments);
|
Daniel@0
|
150 return this;
|
Daniel@0
|
151 },
|
Daniel@0
|
152
|
Daniel@0
|
153 // Tell this object to stop listening to either specific events ... or
|
Daniel@0
|
154 // to every object it's currently listening to.
|
Daniel@0
|
155 stopListening: function(obj, name, callback) {
|
Daniel@0
|
156 var listeningTo = this._listeningTo;
|
Daniel@0
|
157 if (!listeningTo) return this;
|
Daniel@0
|
158 var remove = !name && !callback;
|
Daniel@0
|
159 if (!callback && typeof name === 'object') callback = this;
|
Daniel@0
|
160 if (obj) (listeningTo = {})[obj._listenId] = obj;
|
Daniel@0
|
161 for (var id in listeningTo) {
|
Daniel@0
|
162 obj = listeningTo[id];
|
Daniel@0
|
163 obj.off(name, callback, this);
|
Daniel@0
|
164 if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
|
Daniel@0
|
165 }
|
Daniel@0
|
166 return this;
|
Daniel@0
|
167 }
|
Daniel@0
|
168
|
Daniel@0
|
169 };
|
Daniel@0
|
170
|
Daniel@0
|
171 // Regular expression used to split event strings.
|
Daniel@0
|
172 var eventSplitter = /\s+/;
|
Daniel@0
|
173
|
Daniel@0
|
174 // Implement fancy features of the Events API such as multiple event
|
Daniel@0
|
175 // names `"change blur"` and jQuery-style event maps `{change: action}`
|
Daniel@0
|
176 // in terms of the existing API.
|
Daniel@0
|
177 var eventsApi = function(obj, action, name, rest) {
|
Daniel@0
|
178 if (!name) return true;
|
Daniel@0
|
179
|
Daniel@0
|
180 // Handle event maps.
|
Daniel@0
|
181 if (typeof name === 'object') {
|
Daniel@0
|
182 for (var key in name) {
|
Daniel@0
|
183 obj[action].apply(obj, [key, name[key]].concat(rest));
|
Daniel@0
|
184 }
|
Daniel@0
|
185 return false;
|
Daniel@0
|
186 }
|
Daniel@0
|
187
|
Daniel@0
|
188 // Handle space separated event names.
|
Daniel@0
|
189 if (eventSplitter.test(name)) {
|
Daniel@0
|
190 var names = name.split(eventSplitter);
|
Daniel@0
|
191 for (var i = 0, l = names.length; i < l; i++) {
|
Daniel@0
|
192 obj[action].apply(obj, [names[i]].concat(rest));
|
Daniel@0
|
193 }
|
Daniel@0
|
194 return false;
|
Daniel@0
|
195 }
|
Daniel@0
|
196
|
Daniel@0
|
197 return true;
|
Daniel@0
|
198 };
|
Daniel@0
|
199
|
Daniel@0
|
200 // A difficult-to-believe, but optimized internal dispatch function for
|
Daniel@0
|
201 // triggering events. Tries to keep the usual cases speedy (most internal
|
Daniel@0
|
202 // Backbone events have 3 arguments).
|
Daniel@0
|
203 var triggerEvents = function(events, args) {
|
Daniel@0
|
204 var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
|
Daniel@0
|
205 switch (args.length) {
|
Daniel@0
|
206 case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
|
Daniel@0
|
207 case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
|
Daniel@0
|
208 case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
|
Daniel@0
|
209 case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
|
Daniel@0
|
210 default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
|
Daniel@0
|
211 }
|
Daniel@0
|
212 };
|
Daniel@0
|
213
|
Daniel@0
|
214 var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
|
Daniel@0
|
215
|
Daniel@0
|
216 // Inversion-of-control versions of `on` and `once`. Tell *this* object to
|
Daniel@0
|
217 // listen to an event in another object ... keeping track of what it's
|
Daniel@0
|
218 // listening to.
|
Daniel@0
|
219 _.each(listenMethods, function(implementation, method) {
|
Daniel@0
|
220 Events[method] = function(obj, name, callback) {
|
Daniel@0
|
221 var listeningTo = this._listeningTo || (this._listeningTo = {});
|
Daniel@0
|
222 var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
|
Daniel@0
|
223 listeningTo[id] = obj;
|
Daniel@0
|
224 if (!callback && typeof name === 'object') callback = this;
|
Daniel@0
|
225 obj[implementation](name, callback, this);
|
Daniel@0
|
226 return this;
|
Daniel@0
|
227 };
|
Daniel@0
|
228 });
|
Daniel@0
|
229
|
Daniel@0
|
230 // Aliases for backwards compatibility.
|
Daniel@0
|
231 Events.bind = Events.on;
|
Daniel@0
|
232 Events.unbind = Events.off;
|
Daniel@0
|
233
|
Daniel@0
|
234 // Allow the `Backbone` object to serve as a global event bus, for folks who
|
Daniel@0
|
235 // want global "pubsub" in a convenient place.
|
Daniel@0
|
236 _.extend(Backbone, Events);
|
Daniel@0
|
237
|
Daniel@0
|
238 // Backbone.Model
|
Daniel@0
|
239 // --------------
|
Daniel@0
|
240
|
Daniel@0
|
241 // Backbone **Models** are the basic data object in the framework --
|
Daniel@0
|
242 // frequently representing a row in a table in a database on your server.
|
Daniel@0
|
243 // A discrete chunk of data and a bunch of useful, related methods for
|
Daniel@0
|
244 // performing computations and transformations on that data.
|
Daniel@0
|
245
|
Daniel@0
|
246 // Create a new model with the specified attributes. A client id (`cid`)
|
Daniel@0
|
247 // is automatically generated and assigned for you.
|
Daniel@0
|
248 var Model = Backbone.Model = function(attributes, options) {
|
Daniel@0
|
249 var attrs = attributes || {};
|
Daniel@0
|
250 options || (options = {});
|
Daniel@0
|
251 this.cid = _.uniqueId('c');
|
Daniel@0
|
252 this.attributes = {};
|
Daniel@0
|
253 if (options.collection) this.collection = options.collection;
|
Daniel@0
|
254 if (options.parse) attrs = this.parse(attrs, options) || {};
|
Daniel@0
|
255 attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
|
Daniel@0
|
256 this.set(attrs, options);
|
Daniel@0
|
257 this.changed = {};
|
Daniel@0
|
258 this.initialize.apply(this, arguments);
|
Daniel@0
|
259 };
|
Daniel@0
|
260
|
Daniel@0
|
261 // Attach all inheritable methods to the Model prototype.
|
Daniel@0
|
262 _.extend(Model.prototype, Events, {
|
Daniel@0
|
263
|
Daniel@0
|
264 // A hash of attributes whose current and previous value differ.
|
Daniel@0
|
265 changed: null,
|
Daniel@0
|
266
|
Daniel@0
|
267 // The value returned during the last failed validation.
|
Daniel@0
|
268 validationError: null,
|
Daniel@0
|
269
|
Daniel@0
|
270 // The default name for the JSON `id` attribute is `"id"`. MongoDB and
|
Daniel@0
|
271 // CouchDB users may want to set this to `"_id"`.
|
Daniel@0
|
272 idAttribute: 'id',
|
Daniel@0
|
273
|
Daniel@0
|
274 // Initialize is an empty function by default. Override it with your own
|
Daniel@0
|
275 // initialization logic.
|
Daniel@0
|
276 initialize: function(){},
|
Daniel@0
|
277
|
Daniel@0
|
278 // Return a copy of the model's `attributes` object.
|
Daniel@0
|
279 toJSON: function(options) {
|
Daniel@0
|
280 return _.clone(this.attributes);
|
Daniel@0
|
281 },
|
Daniel@0
|
282
|
Daniel@0
|
283 // Proxy `Backbone.sync` by default -- but override this if you need
|
Daniel@0
|
284 // custom syncing semantics for *this* particular model.
|
Daniel@0
|
285 sync: function() {
|
Daniel@0
|
286 return Backbone.sync.apply(this, arguments);
|
Daniel@0
|
287 },
|
Daniel@0
|
288
|
Daniel@0
|
289 // Get the value of an attribute.
|
Daniel@0
|
290 get: function(attr) {
|
Daniel@0
|
291 return this.attributes[attr];
|
Daniel@0
|
292 },
|
Daniel@0
|
293
|
Daniel@0
|
294 // Get the HTML-escaped value of an attribute.
|
Daniel@0
|
295 escape: function(attr) {
|
Daniel@0
|
296 return _.escape(this.get(attr));
|
Daniel@0
|
297 },
|
Daniel@0
|
298
|
Daniel@0
|
299 // Returns `true` if the attribute contains a value that is not null
|
Daniel@0
|
300 // or undefined.
|
Daniel@0
|
301 has: function(attr) {
|
Daniel@0
|
302 return this.get(attr) != null;
|
Daniel@0
|
303 },
|
Daniel@0
|
304
|
Daniel@0
|
305 // Set a hash of model attributes on the object, firing `"change"`. This is
|
Daniel@0
|
306 // the core primitive operation of a model, updating the data and notifying
|
Daniel@0
|
307 // anyone who needs to know about the change in state. The heart of the beast.
|
Daniel@0
|
308 set: function(key, val, options) {
|
Daniel@0
|
309 var attr, attrs, unset, changes, silent, changing, prev, current;
|
Daniel@0
|
310 if (key == null) return this;
|
Daniel@0
|
311
|
Daniel@0
|
312 // Handle both `"key", value` and `{key: value}` -style arguments.
|
Daniel@0
|
313 if (typeof key === 'object') {
|
Daniel@0
|
314 attrs = key;
|
Daniel@0
|
315 options = val;
|
Daniel@0
|
316 } else {
|
Daniel@0
|
317 (attrs = {})[key] = val;
|
Daniel@0
|
318 }
|
Daniel@0
|
319
|
Daniel@0
|
320 options || (options = {});
|
Daniel@0
|
321
|
Daniel@0
|
322 // Run validation.
|
Daniel@0
|
323 if (!this._validate(attrs, options)) return false;
|
Daniel@0
|
324
|
Daniel@0
|
325 // Extract attributes and options.
|
Daniel@0
|
326 unset = options.unset;
|
Daniel@0
|
327 silent = options.silent;
|
Daniel@0
|
328 changes = [];
|
Daniel@0
|
329 changing = this._changing;
|
Daniel@0
|
330 this._changing = true;
|
Daniel@0
|
331
|
Daniel@0
|
332 if (!changing) {
|
Daniel@0
|
333 this._previousAttributes = _.clone(this.attributes);
|
Daniel@0
|
334 this.changed = {};
|
Daniel@0
|
335 }
|
Daniel@0
|
336 current = this.attributes, prev = this._previousAttributes;
|
Daniel@0
|
337
|
Daniel@0
|
338 // Check for changes of `id`.
|
Daniel@0
|
339 if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
|
Daniel@0
|
340
|
Daniel@0
|
341 // For each `set` attribute, update or delete the current value.
|
Daniel@0
|
342 for (attr in attrs) {
|
Daniel@0
|
343 val = attrs[attr];
|
Daniel@0
|
344 if (!_.isEqual(current[attr], val)) changes.push(attr);
|
Daniel@0
|
345 if (!_.isEqual(prev[attr], val)) {
|
Daniel@0
|
346 this.changed[attr] = val;
|
Daniel@0
|
347 } else {
|
Daniel@0
|
348 delete this.changed[attr];
|
Daniel@0
|
349 }
|
Daniel@0
|
350 unset ? delete current[attr] : current[attr] = val;
|
Daniel@0
|
351 }
|
Daniel@0
|
352
|
Daniel@0
|
353 // Trigger all relevant attribute changes.
|
Daniel@0
|
354 if (!silent) {
|
Daniel@0
|
355 if (changes.length) this._pending = options;
|
Daniel@0
|
356 for (var i = 0, l = changes.length; i < l; i++) {
|
Daniel@0
|
357 this.trigger('change:' + changes[i], this, current[changes[i]], options);
|
Daniel@0
|
358 }
|
Daniel@0
|
359 }
|
Daniel@0
|
360
|
Daniel@0
|
361 // You might be wondering why there's a `while` loop here. Changes can
|
Daniel@0
|
362 // be recursively nested within `"change"` events.
|
Daniel@0
|
363 if (changing) return this;
|
Daniel@0
|
364 if (!silent) {
|
Daniel@0
|
365 while (this._pending) {
|
Daniel@0
|
366 options = this._pending;
|
Daniel@0
|
367 this._pending = false;
|
Daniel@0
|
368 this.trigger('change', this, options);
|
Daniel@0
|
369 }
|
Daniel@0
|
370 }
|
Daniel@0
|
371 this._pending = false;
|
Daniel@0
|
372 this._changing = false;
|
Daniel@0
|
373 return this;
|
Daniel@0
|
374 },
|
Daniel@0
|
375
|
Daniel@0
|
376 // Remove an attribute from the model, firing `"change"`. `unset` is a noop
|
Daniel@0
|
377 // if the attribute doesn't exist.
|
Daniel@0
|
378 unset: function(attr, options) {
|
Daniel@0
|
379 return this.set(attr, void 0, _.extend({}, options, {unset: true}));
|
Daniel@0
|
380 },
|
Daniel@0
|
381
|
Daniel@0
|
382 // Clear all attributes on the model, firing `"change"`.
|
Daniel@0
|
383 clear: function(options) {
|
Daniel@0
|
384 var attrs = {};
|
Daniel@0
|
385 for (var key in this.attributes) attrs[key] = void 0;
|
Daniel@0
|
386 return this.set(attrs, _.extend({}, options, {unset: true}));
|
Daniel@0
|
387 },
|
Daniel@0
|
388
|
Daniel@0
|
389 // Determine if the model has changed since the last `"change"` event.
|
Daniel@0
|
390 // If you specify an attribute name, determine if that attribute has changed.
|
Daniel@0
|
391 hasChanged: function(attr) {
|
Daniel@0
|
392 if (attr == null) return !_.isEmpty(this.changed);
|
Daniel@0
|
393 return _.has(this.changed, attr);
|
Daniel@0
|
394 },
|
Daniel@0
|
395
|
Daniel@0
|
396 // Return an object containing all the attributes that have changed, or
|
Daniel@0
|
397 // false if there are no changed attributes. Useful for determining what
|
Daniel@0
|
398 // parts of a view need to be updated and/or what attributes need to be
|
Daniel@0
|
399 // persisted to the server. Unset attributes will be set to undefined.
|
Daniel@0
|
400 // You can also pass an attributes object to diff against the model,
|
Daniel@0
|
401 // determining if there *would be* a change.
|
Daniel@0
|
402 changedAttributes: function(diff) {
|
Daniel@0
|
403 if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
|
Daniel@0
|
404 var val, changed = false;
|
Daniel@0
|
405 var old = this._changing ? this._previousAttributes : this.attributes;
|
Daniel@0
|
406 for (var attr in diff) {
|
Daniel@0
|
407 if (_.isEqual(old[attr], (val = diff[attr]))) continue;
|
Daniel@0
|
408 (changed || (changed = {}))[attr] = val;
|
Daniel@0
|
409 }
|
Daniel@0
|
410 return changed;
|
Daniel@0
|
411 },
|
Daniel@0
|
412
|
Daniel@0
|
413 // Get the previous value of an attribute, recorded at the time the last
|
Daniel@0
|
414 // `"change"` event was fired.
|
Daniel@0
|
415 previous: function(attr) {
|
Daniel@0
|
416 if (attr == null || !this._previousAttributes) return null;
|
Daniel@0
|
417 return this._previousAttributes[attr];
|
Daniel@0
|
418 },
|
Daniel@0
|
419
|
Daniel@0
|
420 // Get all of the attributes of the model at the time of the previous
|
Daniel@0
|
421 // `"change"` event.
|
Daniel@0
|
422 previousAttributes: function() {
|
Daniel@0
|
423 return _.clone(this._previousAttributes);
|
Daniel@0
|
424 },
|
Daniel@0
|
425
|
Daniel@0
|
426 // Fetch the model from the server. If the server's representation of the
|
Daniel@0
|
427 // model differs from its current attributes, they will be overridden,
|
Daniel@0
|
428 // triggering a `"change"` event.
|
Daniel@0
|
429 fetch: function(options) {
|
Daniel@0
|
430 options = options ? _.clone(options) : {};
|
Daniel@0
|
431 if (options.parse === void 0) options.parse = true;
|
Daniel@0
|
432 var model = this;
|
Daniel@0
|
433 var success = options.success;
|
Daniel@0
|
434 options.success = function(resp) {
|
Daniel@0
|
435 if (!model.set(model.parse(resp, options), options)) return false;
|
Daniel@0
|
436 if (success) success(model, resp, options);
|
Daniel@0
|
437 model.trigger('sync', model, resp, options);
|
Daniel@0
|
438 };
|
Daniel@0
|
439 wrapError(this, options);
|
Daniel@0
|
440 return this.sync('read', this, options);
|
Daniel@0
|
441 },
|
Daniel@0
|
442
|
Daniel@0
|
443 // Set a hash of model attributes, and sync the model to the server.
|
Daniel@0
|
444 // If the server returns an attributes hash that differs, the model's
|
Daniel@0
|
445 // state will be `set` again.
|
Daniel@0
|
446 save: function(key, val, options) {
|
Daniel@0
|
447 var attrs, method, xhr, attributes = this.attributes;
|
Daniel@0
|
448
|
Daniel@0
|
449 // Handle both `"key", value` and `{key: value}` -style arguments.
|
Daniel@0
|
450 if (key == null || typeof key === 'object') {
|
Daniel@0
|
451 attrs = key;
|
Daniel@0
|
452 options = val;
|
Daniel@0
|
453 } else {
|
Daniel@0
|
454 (attrs = {})[key] = val;
|
Daniel@0
|
455 }
|
Daniel@0
|
456
|
Daniel@0
|
457 options = _.extend({validate: true}, options);
|
Daniel@0
|
458
|
Daniel@0
|
459 // If we're not waiting and attributes exist, save acts as
|
Daniel@0
|
460 // `set(attr).save(null, opts)` with validation. Otherwise, check if
|
Daniel@0
|
461 // the model will be valid when the attributes, if any, are set.
|
Daniel@0
|
462 if (attrs && !options.wait) {
|
Daniel@0
|
463 if (!this.set(attrs, options)) return false;
|
Daniel@0
|
464 } else {
|
Daniel@0
|
465 if (!this._validate(attrs, options)) return false;
|
Daniel@0
|
466 }
|
Daniel@0
|
467
|
Daniel@0
|
468 // Set temporary attributes if `{wait: true}`.
|
Daniel@0
|
469 if (attrs && options.wait) {
|
Daniel@0
|
470 this.attributes = _.extend({}, attributes, attrs);
|
Daniel@0
|
471 }
|
Daniel@0
|
472
|
Daniel@0
|
473 // After a successful server-side save, the client is (optionally)
|
Daniel@0
|
474 // updated with the server-side state.
|
Daniel@0
|
475 if (options.parse === void 0) options.parse = true;
|
Daniel@0
|
476 var model = this;
|
Daniel@0
|
477 var success = options.success;
|
Daniel@0
|
478 options.success = function(resp) {
|
Daniel@0
|
479 // Ensure attributes are restored during synchronous saves.
|
Daniel@0
|
480 model.attributes = attributes;
|
Daniel@0
|
481 var serverAttrs = model.parse(resp, options);
|
Daniel@0
|
482 if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
|
Daniel@0
|
483 if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
|
Daniel@0
|
484 return false;
|
Daniel@0
|
485 }
|
Daniel@0
|
486 if (success) success(model, resp, options);
|
Daniel@0
|
487 model.trigger('sync', model, resp, options);
|
Daniel@0
|
488 };
|
Daniel@0
|
489 wrapError(this, options);
|
Daniel@0
|
490
|
Daniel@0
|
491 method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
|
Daniel@0
|
492 if (method === 'patch') options.attrs = attrs;
|
Daniel@0
|
493 xhr = this.sync(method, this, options);
|
Daniel@0
|
494
|
Daniel@0
|
495 // Restore attributes.
|
Daniel@0
|
496 if (attrs && options.wait) this.attributes = attributes;
|
Daniel@0
|
497
|
Daniel@0
|
498 return xhr;
|
Daniel@0
|
499 },
|
Daniel@0
|
500
|
Daniel@0
|
501 // Destroy this model on the server if it was already persisted.
|
Daniel@0
|
502 // Optimistically removes the model from its collection, if it has one.
|
Daniel@0
|
503 // If `wait: true` is passed, waits for the server to respond before removal.
|
Daniel@0
|
504 destroy: function(options) {
|
Daniel@0
|
505 options = options ? _.clone(options) : {};
|
Daniel@0
|
506 var model = this;
|
Daniel@0
|
507 var success = options.success;
|
Daniel@0
|
508
|
Daniel@0
|
509 var destroy = function() {
|
Daniel@0
|
510 model.trigger('destroy', model, model.collection, options);
|
Daniel@0
|
511 };
|
Daniel@0
|
512
|
Daniel@0
|
513 options.success = function(resp) {
|
Daniel@0
|
514 if (options.wait || model.isNew()) destroy();
|
Daniel@0
|
515 if (success) success(model, resp, options);
|
Daniel@0
|
516 if (!model.isNew()) model.trigger('sync', model, resp, options);
|
Daniel@0
|
517 };
|
Daniel@0
|
518
|
Daniel@0
|
519 if (this.isNew()) {
|
Daniel@0
|
520 options.success();
|
Daniel@0
|
521 return false;
|
Daniel@0
|
522 }
|
Daniel@0
|
523 wrapError(this, options);
|
Daniel@0
|
524
|
Daniel@0
|
525 var xhr = this.sync('delete', this, options);
|
Daniel@0
|
526 if (!options.wait) destroy();
|
Daniel@0
|
527 return xhr;
|
Daniel@0
|
528 },
|
Daniel@0
|
529
|
Daniel@0
|
530 // Default URL for the model's representation on the server -- if you're
|
Daniel@0
|
531 // using Backbone's restful methods, override this to change the endpoint
|
Daniel@0
|
532 // that will be called.
|
Daniel@0
|
533 url: function() {
|
Daniel@0
|
534 var base =
|
Daniel@0
|
535 _.result(this, 'urlRoot') ||
|
Daniel@0
|
536 _.result(this.collection, 'url') ||
|
Daniel@0
|
537 urlError();
|
Daniel@0
|
538 if (this.isNew()) return base;
|
Daniel@0
|
539 return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
|
Daniel@0
|
540 },
|
Daniel@0
|
541
|
Daniel@0
|
542 // **parse** converts a response into the hash of attributes to be `set` on
|
Daniel@0
|
543 // the model. The default implementation is just to pass the response along.
|
Daniel@0
|
544 parse: function(resp, options) {
|
Daniel@0
|
545 return resp;
|
Daniel@0
|
546 },
|
Daniel@0
|
547
|
Daniel@0
|
548 // Create a new model with identical attributes to this one.
|
Daniel@0
|
549 clone: function() {
|
Daniel@0
|
550 return new this.constructor(this.attributes);
|
Daniel@0
|
551 },
|
Daniel@0
|
552
|
Daniel@0
|
553 // A model is new if it has never been saved to the server, and lacks an id.
|
Daniel@0
|
554 isNew: function() {
|
Daniel@0
|
555 return !this.has(this.idAttribute);
|
Daniel@0
|
556 },
|
Daniel@0
|
557
|
Daniel@0
|
558 // Check if the model is currently in a valid state.
|
Daniel@0
|
559 isValid: function(options) {
|
Daniel@0
|
560 return this._validate({}, _.extend(options || {}, { validate: true }));
|
Daniel@0
|
561 },
|
Daniel@0
|
562
|
Daniel@0
|
563 // Run validation against the next complete set of model attributes,
|
Daniel@0
|
564 // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
|
Daniel@0
|
565 _validate: function(attrs, options) {
|
Daniel@0
|
566 if (!options.validate || !this.validate) return true;
|
Daniel@0
|
567 attrs = _.extend({}, this.attributes, attrs);
|
Daniel@0
|
568 var error = this.validationError = this.validate(attrs, options) || null;
|
Daniel@0
|
569 if (!error) return true;
|
Daniel@0
|
570 this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
|
Daniel@0
|
571 return false;
|
Daniel@0
|
572 }
|
Daniel@0
|
573
|
Daniel@0
|
574 });
|
Daniel@0
|
575
|
Daniel@0
|
576 // Underscore methods that we want to implement on the Model.
|
Daniel@0
|
577 var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
|
Daniel@0
|
578
|
Daniel@0
|
579 // Mix in each Underscore method as a proxy to `Model#attributes`.
|
Daniel@0
|
580 _.each(modelMethods, function(method) {
|
Daniel@0
|
581 Model.prototype[method] = function() {
|
Daniel@0
|
582 var args = slice.call(arguments);
|
Daniel@0
|
583 args.unshift(this.attributes);
|
Daniel@0
|
584 return _[method].apply(_, args);
|
Daniel@0
|
585 };
|
Daniel@0
|
586 });
|
Daniel@0
|
587
|
Daniel@0
|
588 // Backbone.Collection
|
Daniel@0
|
589 // -------------------
|
Daniel@0
|
590
|
Daniel@0
|
591 // If models tend to represent a single row of data, a Backbone Collection is
|
Daniel@0
|
592 // more analagous to a table full of data ... or a small slice or page of that
|
Daniel@0
|
593 // table, or a collection of rows that belong together for a particular reason
|
Daniel@0
|
594 // -- all of the messages in this particular folder, all of the documents
|
Daniel@0
|
595 // belonging to this particular author, and so on. Collections maintain
|
Daniel@0
|
596 // indexes of their models, both in order, and for lookup by `id`.
|
Daniel@0
|
597
|
Daniel@0
|
598 // Create a new **Collection**, perhaps to contain a specific type of `model`.
|
Daniel@0
|
599 // If a `comparator` is specified, the Collection will maintain
|
Daniel@0
|
600 // its models in sort order, as they're added and removed.
|
Daniel@0
|
601 var Collection = Backbone.Collection = function(models, options) {
|
Daniel@0
|
602 options || (options = {});
|
Daniel@0
|
603 if (options.model) this.model = options.model;
|
Daniel@0
|
604 if (options.comparator !== void 0) this.comparator = options.comparator;
|
Daniel@0
|
605 this._reset();
|
Daniel@0
|
606 this.initialize.apply(this, arguments);
|
Daniel@0
|
607 if (models) this.reset(models, _.extend({silent: true}, options));
|
Daniel@0
|
608 };
|
Daniel@0
|
609
|
Daniel@0
|
610 // Default options for `Collection#set`.
|
Daniel@0
|
611 var setOptions = {add: true, remove: true, merge: true};
|
Daniel@0
|
612 var addOptions = {add: true, remove: false};
|
Daniel@0
|
613
|
Daniel@0
|
614 // Define the Collection's inheritable methods.
|
Daniel@0
|
615 _.extend(Collection.prototype, Events, {
|
Daniel@0
|
616
|
Daniel@0
|
617 // The default model for a collection is just a **Backbone.Model**.
|
Daniel@0
|
618 // This should be overridden in most cases.
|
Daniel@0
|
619 model: Model,
|
Daniel@0
|
620
|
Daniel@0
|
621 // Initialize is an empty function by default. Override it with your own
|
Daniel@0
|
622 // initialization logic.
|
Daniel@0
|
623 initialize: function(){},
|
Daniel@0
|
624
|
Daniel@0
|
625 // The JSON representation of a Collection is an array of the
|
Daniel@0
|
626 // models' attributes.
|
Daniel@0
|
627 toJSON: function(options) {
|
Daniel@0
|
628 return this.map(function(model){ return model.toJSON(options); });
|
Daniel@0
|
629 },
|
Daniel@0
|
630
|
Daniel@0
|
631 // Proxy `Backbone.sync` by default.
|
Daniel@0
|
632 sync: function() {
|
Daniel@0
|
633 return Backbone.sync.apply(this, arguments);
|
Daniel@0
|
634 },
|
Daniel@0
|
635
|
Daniel@0
|
636 // Add a model, or list of models to the set.
|
Daniel@0
|
637 add: function(models, options) {
|
Daniel@0
|
638 return this.set(models, _.extend({merge: false}, options, addOptions));
|
Daniel@0
|
639 },
|
Daniel@0
|
640
|
Daniel@0
|
641 // Remove a model, or a list of models from the set.
|
Daniel@0
|
642 remove: function(models, options) {
|
Daniel@0
|
643 var singular = !_.isArray(models);
|
Daniel@0
|
644 models = singular ? [models] : _.clone(models);
|
Daniel@0
|
645 options || (options = {});
|
Daniel@0
|
646 var i, l, index, model;
|
Daniel@0
|
647 for (i = 0, l = models.length; i < l; i++) {
|
Daniel@0
|
648 model = models[i] = this.get(models[i]);
|
Daniel@0
|
649 if (!model) continue;
|
Daniel@0
|
650 delete this._byId[model.id];
|
Daniel@0
|
651 delete this._byId[model.cid];
|
Daniel@0
|
652 index = this.indexOf(model);
|
Daniel@0
|
653 this.models.splice(index, 1);
|
Daniel@0
|
654 this.length--;
|
Daniel@0
|
655 if (!options.silent) {
|
Daniel@0
|
656 options.index = index;
|
Daniel@0
|
657 model.trigger('remove', model, this, options);
|
Daniel@0
|
658 }
|
Daniel@0
|
659 this._removeReference(model, options);
|
Daniel@0
|
660 }
|
Daniel@0
|
661 return singular ? models[0] : models;
|
Daniel@0
|
662 },
|
Daniel@0
|
663
|
Daniel@0
|
664 // Update a collection by `set`-ing a new list of models, adding new ones,
|
Daniel@0
|
665 // removing models that are no longer present, and merging models that
|
Daniel@0
|
666 // already exist in the collection, as necessary. Similar to **Model#set**,
|
Daniel@0
|
667 // the core operation for updating the data contained by the collection.
|
Daniel@0
|
668 set: function(models, options) {
|
Daniel@0
|
669 options = _.defaults({}, options, setOptions);
|
Daniel@0
|
670 if (options.parse) models = this.parse(models, options);
|
Daniel@0
|
671 var singular = !_.isArray(models);
|
Daniel@0
|
672 models = singular ? (models ? [models] : []) : _.clone(models);
|
Daniel@0
|
673 var i, l, id, model, attrs, existing, sort;
|
Daniel@0
|
674 var at = options.at;
|
Daniel@0
|
675 var targetModel = this.model;
|
Daniel@0
|
676 var sortable = this.comparator && (at == null) && options.sort !== false;
|
Daniel@0
|
677 var sortAttr = _.isString(this.comparator) ? this.comparator : null;
|
Daniel@0
|
678 var toAdd = [], toRemove = [], modelMap = {};
|
Daniel@0
|
679 var add = options.add, merge = options.merge, remove = options.remove;
|
Daniel@0
|
680 var order = !sortable && add && remove ? [] : false;
|
Daniel@0
|
681
|
Daniel@0
|
682 // Turn bare objects into model references, and prevent invalid models
|
Daniel@0
|
683 // from being added.
|
Daniel@0
|
684 for (i = 0, l = models.length; i < l; i++) {
|
Daniel@0
|
685 attrs = models[i] || {};
|
Daniel@0
|
686 if (attrs instanceof Model) {
|
Daniel@0
|
687 id = model = attrs;
|
Daniel@0
|
688 } else {
|
Daniel@0
|
689 id = attrs[targetModel.prototype.idAttribute || 'id'];
|
Daniel@0
|
690 }
|
Daniel@0
|
691
|
Daniel@0
|
692 // If a duplicate is found, prevent it from being added and
|
Daniel@0
|
693 // optionally merge it into the existing model.
|
Daniel@0
|
694 if (existing = this.get(id)) {
|
Daniel@0
|
695 if (remove) modelMap[existing.cid] = true;
|
Daniel@0
|
696 if (merge) {
|
Daniel@0
|
697 attrs = attrs === model ? model.attributes : attrs;
|
Daniel@0
|
698 if (options.parse) attrs = existing.parse(attrs, options);
|
Daniel@0
|
699 existing.set(attrs, options);
|
Daniel@0
|
700 if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
|
Daniel@0
|
701 }
|
Daniel@0
|
702 models[i] = existing;
|
Daniel@0
|
703
|
Daniel@0
|
704 // If this is a new, valid model, push it to the `toAdd` list.
|
Daniel@0
|
705 } else if (add) {
|
Daniel@0
|
706 model = models[i] = this._prepareModel(attrs, options);
|
Daniel@0
|
707 if (!model) continue;
|
Daniel@0
|
708 toAdd.push(model);
|
Daniel@0
|
709 this._addReference(model, options);
|
Daniel@0
|
710 }
|
Daniel@0
|
711
|
Daniel@0
|
712 // Do not add multiple models with the same `id`.
|
Daniel@0
|
713 model = existing || model;
|
Daniel@0
|
714 if (order && (model.isNew() || !modelMap[model.id])) order.push(model);
|
Daniel@0
|
715 modelMap[model.id] = true;
|
Daniel@0
|
716 }
|
Daniel@0
|
717
|
Daniel@0
|
718 // Remove nonexistent models if appropriate.
|
Daniel@0
|
719 if (remove) {
|
Daniel@0
|
720 for (i = 0, l = this.length; i < l; ++i) {
|
Daniel@0
|
721 if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
|
Daniel@0
|
722 }
|
Daniel@0
|
723 if (toRemove.length) this.remove(toRemove, options);
|
Daniel@0
|
724 }
|
Daniel@0
|
725
|
Daniel@0
|
726 // See if sorting is needed, update `length` and splice in new models.
|
Daniel@0
|
727 if (toAdd.length || (order && order.length)) {
|
Daniel@0
|
728 if (sortable) sort = true;
|
Daniel@0
|
729 this.length += toAdd.length;
|
Daniel@0
|
730 if (at != null) {
|
Daniel@0
|
731 for (i = 0, l = toAdd.length; i < l; i++) {
|
Daniel@0
|
732 this.models.splice(at + i, 0, toAdd[i]);
|
Daniel@0
|
733 }
|
Daniel@0
|
734 } else {
|
Daniel@0
|
735 if (order) this.models.length = 0;
|
Daniel@0
|
736 var orderedModels = order || toAdd;
|
Daniel@0
|
737 for (i = 0, l = orderedModels.length; i < l; i++) {
|
Daniel@0
|
738 this.models.push(orderedModels[i]);
|
Daniel@0
|
739 }
|
Daniel@0
|
740 }
|
Daniel@0
|
741 }
|
Daniel@0
|
742
|
Daniel@0
|
743 // Silently sort the collection if appropriate.
|
Daniel@0
|
744 if (sort) this.sort({silent: true});
|
Daniel@0
|
745
|
Daniel@0
|
746 // Unless silenced, it's time to fire all appropriate add/sort events.
|
Daniel@0
|
747 if (!options.silent) {
|
Daniel@0
|
748 for (i = 0, l = toAdd.length; i < l; i++) {
|
Daniel@0
|
749 (model = toAdd[i]).trigger('add', model, this, options);
|
Daniel@0
|
750 }
|
Daniel@0
|
751 if (sort || (order && order.length)) this.trigger('sort', this, options);
|
Daniel@0
|
752 }
|
Daniel@0
|
753
|
Daniel@0
|
754 // Return the added (or merged) model (or models).
|
Daniel@0
|
755 return singular ? models[0] : models;
|
Daniel@0
|
756 },
|
Daniel@0
|
757
|
Daniel@0
|
758 // When you have more items than you want to add or remove individually,
|
Daniel@0
|
759 // you can reset the entire set with a new list of models, without firing
|
Daniel@0
|
760 // any granular `add` or `remove` events. Fires `reset` when finished.
|
Daniel@0
|
761 // Useful for bulk operations and optimizations.
|
Daniel@0
|
762 reset: function(models, options) {
|
Daniel@0
|
763 options || (options = {});
|
Daniel@0
|
764 for (var i = 0, l = this.models.length; i < l; i++) {
|
Daniel@0
|
765 this._removeReference(this.models[i], options);
|
Daniel@0
|
766 }
|
Daniel@0
|
767 options.previousModels = this.models;
|
Daniel@0
|
768 this._reset();
|
Daniel@0
|
769 models = this.add(models, _.extend({silent: true}, options));
|
Daniel@0
|
770 if (!options.silent) this.trigger('reset', this, options);
|
Daniel@0
|
771 return models;
|
Daniel@0
|
772 },
|
Daniel@0
|
773
|
Daniel@0
|
774 // Add a model to the end of the collection.
|
Daniel@0
|
775 push: function(model, options) {
|
Daniel@0
|
776 return this.add(model, _.extend({at: this.length}, options));
|
Daniel@0
|
777 },
|
Daniel@0
|
778
|
Daniel@0
|
779 // Remove a model from the end of the collection.
|
Daniel@0
|
780 pop: function(options) {
|
Daniel@0
|
781 var model = this.at(this.length - 1);
|
Daniel@0
|
782 this.remove(model, options);
|
Daniel@0
|
783 return model;
|
Daniel@0
|
784 },
|
Daniel@0
|
785
|
Daniel@0
|
786 // Add a model to the beginning of the collection.
|
Daniel@0
|
787 unshift: function(model, options) {
|
Daniel@0
|
788 return this.add(model, _.extend({at: 0}, options));
|
Daniel@0
|
789 },
|
Daniel@0
|
790
|
Daniel@0
|
791 // Remove a model from the beginning of the collection.
|
Daniel@0
|
792 shift: function(options) {
|
Daniel@0
|
793 var model = this.at(0);
|
Daniel@0
|
794 this.remove(model, options);
|
Daniel@0
|
795 return model;
|
Daniel@0
|
796 },
|
Daniel@0
|
797
|
Daniel@0
|
798 // Slice out a sub-array of models from the collection.
|
Daniel@0
|
799 slice: function() {
|
Daniel@0
|
800 return slice.apply(this.models, arguments);
|
Daniel@0
|
801 },
|
Daniel@0
|
802
|
Daniel@0
|
803 // Get a model from the set by id.
|
Daniel@0
|
804 get: function(obj) {
|
Daniel@0
|
805 if (obj == null) return void 0;
|
Daniel@0
|
806 return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid];
|
Daniel@0
|
807 },
|
Daniel@0
|
808
|
Daniel@0
|
809 // Get the model at the given index.
|
Daniel@0
|
810 at: function(index) {
|
Daniel@0
|
811 return this.models[index];
|
Daniel@0
|
812 },
|
Daniel@0
|
813
|
Daniel@0
|
814 // Return models with matching attributes. Useful for simple cases of
|
Daniel@0
|
815 // `filter`.
|
Daniel@0
|
816 where: function(attrs, first) {
|
Daniel@0
|
817 if (_.isEmpty(attrs)) return first ? void 0 : [];
|
Daniel@0
|
818 return this[first ? 'find' : 'filter'](function(model) {
|
Daniel@0
|
819 for (var key in attrs) {
|
Daniel@0
|
820 if (attrs[key] !== model.get(key)) return false;
|
Daniel@0
|
821 }
|
Daniel@0
|
822 return true;
|
Daniel@0
|
823 });
|
Daniel@0
|
824 },
|
Daniel@0
|
825
|
Daniel@0
|
826 // Return the first model with matching attributes. Useful for simple cases
|
Daniel@0
|
827 // of `find`.
|
Daniel@0
|
828 findWhere: function(attrs) {
|
Daniel@0
|
829 return this.where(attrs, true);
|
Daniel@0
|
830 },
|
Daniel@0
|
831
|
Daniel@0
|
832 // Force the collection to re-sort itself. You don't need to call this under
|
Daniel@0
|
833 // normal circumstances, as the set will maintain sort order as each item
|
Daniel@0
|
834 // is added.
|
Daniel@0
|
835 sort: function(options) {
|
Daniel@0
|
836 if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
|
Daniel@0
|
837 options || (options = {});
|
Daniel@0
|
838
|
Daniel@0
|
839 // Run sort based on type of `comparator`.
|
Daniel@0
|
840 if (_.isString(this.comparator) || this.comparator.length === 1) {
|
Daniel@0
|
841 this.models = this.sortBy(this.comparator, this);
|
Daniel@0
|
842 } else {
|
Daniel@0
|
843 this.models.sort(_.bind(this.comparator, this));
|
Daniel@0
|
844 }
|
Daniel@0
|
845
|
Daniel@0
|
846 if (!options.silent) this.trigger('sort', this, options);
|
Daniel@0
|
847 return this;
|
Daniel@0
|
848 },
|
Daniel@0
|
849
|
Daniel@0
|
850 // Pluck an attribute from each model in the collection.
|
Daniel@0
|
851 pluck: function(attr) {
|
Daniel@0
|
852 return _.invoke(this.models, 'get', attr);
|
Daniel@0
|
853 },
|
Daniel@0
|
854
|
Daniel@0
|
855 // Fetch the default set of models for this collection, resetting the
|
Daniel@0
|
856 // collection when they arrive. If `reset: true` is passed, the response
|
Daniel@0
|
857 // data will be passed through the `reset` method instead of `set`.
|
Daniel@0
|
858 fetch: function(options) {
|
Daniel@0
|
859 options = options ? _.clone(options) : {};
|
Daniel@0
|
860 if (options.parse === void 0) options.parse = true;
|
Daniel@0
|
861 var success = options.success;
|
Daniel@0
|
862 var collection = this;
|
Daniel@0
|
863 options.success = function(resp) {
|
Daniel@0
|
864 var method = options.reset ? 'reset' : 'set';
|
Daniel@0
|
865 collection[method](resp, options);
|
Daniel@0
|
866 if (success) success(collection, resp, options);
|
Daniel@0
|
867 collection.trigger('sync', collection, resp, options);
|
Daniel@0
|
868 };
|
Daniel@0
|
869 wrapError(this, options);
|
Daniel@0
|
870 return this.sync('read', this, options);
|
Daniel@0
|
871 },
|
Daniel@0
|
872
|
Daniel@0
|
873 // Create a new instance of a model in this collection. Add the model to the
|
Daniel@0
|
874 // collection immediately, unless `wait: true` is passed, in which case we
|
Daniel@0
|
875 // wait for the server to agree.
|
Daniel@0
|
876 create: function(model, options) {
|
Daniel@0
|
877 options = options ? _.clone(options) : {};
|
Daniel@0
|
878 if (!(model = this._prepareModel(model, options))) return false;
|
Daniel@0
|
879 if (!options.wait) this.add(model, options);
|
Daniel@0
|
880 var collection = this;
|
Daniel@0
|
881 var success = options.success;
|
Daniel@0
|
882 options.success = function(model, resp) {
|
Daniel@0
|
883 if (options.wait) collection.add(model, options);
|
Daniel@0
|
884 if (success) success(model, resp, options);
|
Daniel@0
|
885 };
|
Daniel@0
|
886 model.save(null, options);
|
Daniel@0
|
887 return model;
|
Daniel@0
|
888 },
|
Daniel@0
|
889
|
Daniel@0
|
890 // **parse** converts a response into a list of models to be added to the
|
Daniel@0
|
891 // collection. The default implementation is just to pass it through.
|
Daniel@0
|
892 parse: function(resp, options) {
|
Daniel@0
|
893 return resp;
|
Daniel@0
|
894 },
|
Daniel@0
|
895
|
Daniel@0
|
896 // Create a new collection with an identical list of models as this one.
|
Daniel@0
|
897 clone: function() {
|
Daniel@0
|
898 return new this.constructor(this.models);
|
Daniel@0
|
899 },
|
Daniel@0
|
900
|
Daniel@0
|
901 // Private method to reset all internal state. Called when the collection
|
Daniel@0
|
902 // is first initialized or reset.
|
Daniel@0
|
903 _reset: function() {
|
Daniel@0
|
904 this.length = 0;
|
Daniel@0
|
905 this.models = [];
|
Daniel@0
|
906 this._byId = {};
|
Daniel@0
|
907 },
|
Daniel@0
|
908
|
Daniel@0
|
909 // Prepare a hash of attributes (or other model) to be added to this
|
Daniel@0
|
910 // collection.
|
Daniel@0
|
911 _prepareModel: function(attrs, options) {
|
Daniel@0
|
912 if (attrs instanceof Model) return attrs;
|
Daniel@0
|
913 options = options ? _.clone(options) : {};
|
Daniel@0
|
914 options.collection = this;
|
Daniel@0
|
915 var model = new this.model(attrs, options);
|
Daniel@0
|
916 if (!model.validationError) return model;
|
Daniel@0
|
917 this.trigger('invalid', this, model.validationError, options);
|
Daniel@0
|
918 return false;
|
Daniel@0
|
919 },
|
Daniel@0
|
920
|
Daniel@0
|
921 // Internal method to create a model's ties to a collection.
|
Daniel@0
|
922 _addReference: function(model, options) {
|
Daniel@0
|
923 this._byId[model.cid] = model;
|
Daniel@0
|
924 if (model.id != null) this._byId[model.id] = model;
|
Daniel@0
|
925 if (!model.collection) model.collection = this;
|
Daniel@0
|
926 model.on('all', this._onModelEvent, this);
|
Daniel@0
|
927 },
|
Daniel@0
|
928
|
Daniel@0
|
929 // Internal method to sever a model's ties to a collection.
|
Daniel@0
|
930 _removeReference: function(model, options) {
|
Daniel@0
|
931 if (this === model.collection) delete model.collection;
|
Daniel@0
|
932 model.off('all', this._onModelEvent, this);
|
Daniel@0
|
933 },
|
Daniel@0
|
934
|
Daniel@0
|
935 // Internal method called every time a model in the set fires an event.
|
Daniel@0
|
936 // Sets need to update their indexes when models change ids. All other
|
Daniel@0
|
937 // events simply proxy through. "add" and "remove" events that originate
|
Daniel@0
|
938 // in other collections are ignored.
|
Daniel@0
|
939 _onModelEvent: function(event, model, collection, options) {
|
Daniel@0
|
940 if ((event === 'add' || event === 'remove') && collection !== this) return;
|
Daniel@0
|
941 if (event === 'destroy') this.remove(model, options);
|
Daniel@0
|
942 if (model && event === 'change:' + model.idAttribute) {
|
Daniel@0
|
943 delete this._byId[model.previous(model.idAttribute)];
|
Daniel@0
|
944 if (model.id != null) this._byId[model.id] = model;
|
Daniel@0
|
945 }
|
Daniel@0
|
946 this.trigger.apply(this, arguments);
|
Daniel@0
|
947 }
|
Daniel@0
|
948
|
Daniel@0
|
949 });
|
Daniel@0
|
950
|
Daniel@0
|
951 // Underscore methods that we want to implement on the Collection.
|
Daniel@0
|
952 // 90% of the core usefulness of Backbone Collections is actually implemented
|
Daniel@0
|
953 // right here:
|
Daniel@0
|
954 var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
|
Daniel@0
|
955 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
|
Daniel@0
|
956 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
|
Daniel@0
|
957 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
|
Daniel@0
|
958 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
|
Daniel@0
|
959 'lastIndexOf', 'isEmpty', 'chain', 'sample'];
|
Daniel@0
|
960
|
Daniel@0
|
961 // Mix in each Underscore method as a proxy to `Collection#models`.
|
Daniel@0
|
962 _.each(methods, function(method) {
|
Daniel@0
|
963 Collection.prototype[method] = function() {
|
Daniel@0
|
964 var args = slice.call(arguments);
|
Daniel@0
|
965 args.unshift(this.models);
|
Daniel@0
|
966 return _[method].apply(_, args);
|
Daniel@0
|
967 };
|
Daniel@0
|
968 });
|
Daniel@0
|
969
|
Daniel@0
|
970 // Underscore methods that take a property name as an argument.
|
Daniel@0
|
971 var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy'];
|
Daniel@0
|
972
|
Daniel@0
|
973 // Use attributes instead of properties.
|
Daniel@0
|
974 _.each(attributeMethods, function(method) {
|
Daniel@0
|
975 Collection.prototype[method] = function(value, context) {
|
Daniel@0
|
976 var iterator = _.isFunction(value) ? value : function(model) {
|
Daniel@0
|
977 return model.get(value);
|
Daniel@0
|
978 };
|
Daniel@0
|
979 return _[method](this.models, iterator, context);
|
Daniel@0
|
980 };
|
Daniel@0
|
981 });
|
Daniel@0
|
982
|
Daniel@0
|
983 // Backbone.View
|
Daniel@0
|
984 // -------------
|
Daniel@0
|
985
|
Daniel@0
|
986 // Backbone Views are almost more convention than they are actual code. A View
|
Daniel@0
|
987 // is simply a JavaScript object that represents a logical chunk of UI in the
|
Daniel@0
|
988 // DOM. This might be a single item, an entire list, a sidebar or panel, or
|
Daniel@0
|
989 // even the surrounding frame which wraps your whole app. Defining a chunk of
|
Daniel@0
|
990 // UI as a **View** allows you to define your DOM events declaratively, without
|
Daniel@0
|
991 // having to worry about render order ... and makes it easy for the view to
|
Daniel@0
|
992 // react to specific changes in the state of your models.
|
Daniel@0
|
993
|
Daniel@0
|
994 // Creating a Backbone.View creates its initial element outside of the DOM,
|
Daniel@0
|
995 // if an existing element is not provided...
|
Daniel@0
|
996 var View = Backbone.View = function(options) {
|
Daniel@0
|
997 this.cid = _.uniqueId('view');
|
Daniel@0
|
998 options || (options = {});
|
Daniel@0
|
999 _.extend(this, _.pick(options, viewOptions));
|
Daniel@0
|
1000 this._ensureElement();
|
Daniel@0
|
1001 this.initialize.apply(this, arguments);
|
Daniel@0
|
1002 this.delegateEvents();
|
Daniel@0
|
1003 };
|
Daniel@0
|
1004
|
Daniel@0
|
1005 // Cached regex to split keys for `delegate`.
|
Daniel@0
|
1006 var delegateEventSplitter = /^(\S+)\s*(.*)$/;
|
Daniel@0
|
1007
|
Daniel@0
|
1008 // List of view options to be merged as properties.
|
Daniel@0
|
1009 var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
|
Daniel@0
|
1010
|
Daniel@0
|
1011 // Set up all inheritable **Backbone.View** properties and methods.
|
Daniel@0
|
1012 _.extend(View.prototype, Events, {
|
Daniel@0
|
1013
|
Daniel@0
|
1014 // The default `tagName` of a View's element is `"div"`.
|
Daniel@0
|
1015 tagName: 'div',
|
Daniel@0
|
1016
|
Daniel@0
|
1017 // jQuery delegate for element lookup, scoped to DOM elements within the
|
Daniel@0
|
1018 // current view. This should be preferred to global lookups where possible.
|
Daniel@0
|
1019 $: function(selector) {
|
Daniel@0
|
1020 return this.$el.find(selector);
|
Daniel@0
|
1021 },
|
Daniel@0
|
1022
|
Daniel@0
|
1023 // Initialize is an empty function by default. Override it with your own
|
Daniel@0
|
1024 // initialization logic.
|
Daniel@0
|
1025 initialize: function(){},
|
Daniel@0
|
1026
|
Daniel@0
|
1027 // **render** is the core function that your view should override, in order
|
Daniel@0
|
1028 // to populate its element (`this.el`), with the appropriate HTML. The
|
Daniel@0
|
1029 // convention is for **render** to always return `this`.
|
Daniel@0
|
1030 render: function() {
|
Daniel@0
|
1031 return this;
|
Daniel@0
|
1032 },
|
Daniel@0
|
1033
|
Daniel@0
|
1034 // Remove this view by taking the element out of the DOM, and removing any
|
Daniel@0
|
1035 // applicable Backbone.Events listeners.
|
Daniel@0
|
1036 remove: function() {
|
Daniel@0
|
1037 this.$el.remove();
|
Daniel@0
|
1038 this.stopListening();
|
Daniel@0
|
1039 return this;
|
Daniel@0
|
1040 },
|
Daniel@0
|
1041
|
Daniel@0
|
1042 // Change the view's element (`this.el` property), including event
|
Daniel@0
|
1043 // re-delegation.
|
Daniel@0
|
1044 setElement: function(element, delegate) {
|
Daniel@0
|
1045 if (this.$el) this.undelegateEvents();
|
Daniel@0
|
1046 this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
|
Daniel@0
|
1047 this.el = this.$el[0];
|
Daniel@0
|
1048 if (delegate !== false) this.delegateEvents();
|
Daniel@0
|
1049 return this;
|
Daniel@0
|
1050 },
|
Daniel@0
|
1051
|
Daniel@0
|
1052 // Set callbacks, where `this.events` is a hash of
|
Daniel@0
|
1053 //
|
Daniel@0
|
1054 // *{"event selector": "callback"}*
|
Daniel@0
|
1055 //
|
Daniel@0
|
1056 // {
|
Daniel@0
|
1057 // 'mousedown .title': 'edit',
|
Daniel@0
|
1058 // 'click .button': 'save',
|
Daniel@0
|
1059 // 'click .open': function(e) { ... }
|
Daniel@0
|
1060 // }
|
Daniel@0
|
1061 //
|
Daniel@0
|
1062 // pairs. Callbacks will be bound to the view, with `this` set properly.
|
Daniel@0
|
1063 // Uses event delegation for efficiency.
|
Daniel@0
|
1064 // Omitting the selector binds the event to `this.el`.
|
Daniel@0
|
1065 // This only works for delegate-able events: not `focus`, `blur`, and
|
Daniel@0
|
1066 // not `change`, `submit`, and `reset` in Internet Explorer.
|
Daniel@0
|
1067 delegateEvents: function(events) {
|
Daniel@0
|
1068 if (!(events || (events = _.result(this, 'events')))) return this;
|
Daniel@0
|
1069 this.undelegateEvents();
|
Daniel@0
|
1070 for (var key in events) {
|
Daniel@0
|
1071 var method = events[key];
|
Daniel@0
|
1072 if (!_.isFunction(method)) method = this[events[key]];
|
Daniel@0
|
1073 if (!method) continue;
|
Daniel@0
|
1074
|
Daniel@0
|
1075 var match = key.match(delegateEventSplitter);
|
Daniel@0
|
1076 var eventName = match[1], selector = match[2];
|
Daniel@0
|
1077 method = _.bind(method, this);
|
Daniel@0
|
1078 eventName += '.delegateEvents' + this.cid;
|
Daniel@0
|
1079 if (selector === '') {
|
Daniel@0
|
1080 this.$el.on(eventName, method);
|
Daniel@0
|
1081 } else {
|
Daniel@0
|
1082 this.$el.on(eventName, selector, method);
|
Daniel@0
|
1083 }
|
Daniel@0
|
1084 }
|
Daniel@0
|
1085 return this;
|
Daniel@0
|
1086 },
|
Daniel@0
|
1087
|
Daniel@0
|
1088 // Clears all callbacks previously bound to the view with `delegateEvents`.
|
Daniel@0
|
1089 // You usually don't need to use this, but may wish to if you have multiple
|
Daniel@0
|
1090 // Backbone views attached to the same DOM element.
|
Daniel@0
|
1091 undelegateEvents: function() {
|
Daniel@0
|
1092 this.$el.off('.delegateEvents' + this.cid);
|
Daniel@0
|
1093 return this;
|
Daniel@0
|
1094 },
|
Daniel@0
|
1095
|
Daniel@0
|
1096 // Ensure that the View has a DOM element to render into.
|
Daniel@0
|
1097 // If `this.el` is a string, pass it through `$()`, take the first
|
Daniel@0
|
1098 // matching element, and re-assign it to `el`. Otherwise, create
|
Daniel@0
|
1099 // an element from the `id`, `className` and `tagName` properties.
|
Daniel@0
|
1100 _ensureElement: function() {
|
Daniel@0
|
1101 if (!this.el) {
|
Daniel@0
|
1102 var attrs = _.extend({}, _.result(this, 'attributes'));
|
Daniel@0
|
1103 if (this.id) attrs.id = _.result(this, 'id');
|
Daniel@0
|
1104 if (this.className) attrs['class'] = _.result(this, 'className');
|
Daniel@0
|
1105 var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
|
Daniel@0
|
1106 this.setElement($el, false);
|
Daniel@0
|
1107 } else {
|
Daniel@0
|
1108 this.setElement(_.result(this, 'el'), false);
|
Daniel@0
|
1109 }
|
Daniel@0
|
1110 }
|
Daniel@0
|
1111
|
Daniel@0
|
1112 });
|
Daniel@0
|
1113
|
Daniel@0
|
1114 // Backbone.sync
|
Daniel@0
|
1115 // -------------
|
Daniel@0
|
1116
|
Daniel@0
|
1117 // Override this function to change the manner in which Backbone persists
|
Daniel@0
|
1118 // models to the server. You will be passed the type of request, and the
|
Daniel@0
|
1119 // model in question. By default, makes a RESTful Ajax request
|
Daniel@0
|
1120 // to the model's `url()`. Some possible customizations could be:
|
Daniel@0
|
1121 //
|
Daniel@0
|
1122 // * Use `setTimeout` to batch rapid-fire updates into a single request.
|
Daniel@0
|
1123 // * Send up the models as XML instead of JSON.
|
Daniel@0
|
1124 // * Persist models via WebSockets instead of Ajax.
|
Daniel@0
|
1125 //
|
Daniel@0
|
1126 // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
|
Daniel@0
|
1127 // as `POST`, with a `_method` parameter containing the true HTTP method,
|
Daniel@0
|
1128 // as well as all requests with the body as `application/x-www-form-urlencoded`
|
Daniel@0
|
1129 // instead of `application/json` with the model in a param named `model`.
|
Daniel@0
|
1130 // Useful when interfacing with server-side languages like **PHP** that make
|
Daniel@0
|
1131 // it difficult to read the body of `PUT` requests.
|
Daniel@0
|
1132 Backbone.sync = function(method, model, options) {
|
Daniel@0
|
1133 var type = methodMap[method];
|
Daniel@0
|
1134
|
Daniel@0
|
1135 // Default options, unless specified.
|
Daniel@0
|
1136 _.defaults(options || (options = {}), {
|
Daniel@0
|
1137 emulateHTTP: Backbone.emulateHTTP,
|
Daniel@0
|
1138 emulateJSON: Backbone.emulateJSON
|
Daniel@0
|
1139 });
|
Daniel@0
|
1140
|
Daniel@0
|
1141 // Default JSON-request options.
|
Daniel@0
|
1142 var params = {type: type, dataType: 'json'};
|
Daniel@0
|
1143
|
Daniel@0
|
1144 // Ensure that we have a URL.
|
Daniel@0
|
1145 if (!options.url) {
|
Daniel@0
|
1146 params.url = _.result(model, 'url') || urlError();
|
Daniel@0
|
1147 }
|
Daniel@0
|
1148
|
Daniel@0
|
1149 // Ensure that we have the appropriate request data.
|
Daniel@0
|
1150 if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
|
Daniel@0
|
1151 params.contentType = 'application/json';
|
Daniel@0
|
1152 params.data = JSON.stringify(options.attrs || model.toJSON(options));
|
Daniel@0
|
1153 }
|
Daniel@0
|
1154
|
Daniel@0
|
1155 // For older servers, emulate JSON by encoding the request into an HTML-form.
|
Daniel@0
|
1156 if (options.emulateJSON) {
|
Daniel@0
|
1157 params.contentType = 'application/x-www-form-urlencoded';
|
Daniel@0
|
1158 params.data = params.data ? {model: params.data} : {};
|
Daniel@0
|
1159 }
|
Daniel@0
|
1160
|
Daniel@0
|
1161 // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
|
Daniel@0
|
1162 // And an `X-HTTP-Method-Override` header.
|
Daniel@0
|
1163 if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
|
Daniel@0
|
1164 params.type = 'POST';
|
Daniel@0
|
1165 if (options.emulateJSON) params.data._method = type;
|
Daniel@0
|
1166 var beforeSend = options.beforeSend;
|
Daniel@0
|
1167 options.beforeSend = function(xhr) {
|
Daniel@0
|
1168 xhr.setRequestHeader('X-HTTP-Method-Override', type);
|
Daniel@0
|
1169 if (beforeSend) return beforeSend.apply(this, arguments);
|
Daniel@0
|
1170 };
|
Daniel@0
|
1171 }
|
Daniel@0
|
1172
|
Daniel@0
|
1173 // Don't process data on a non-GET request.
|
Daniel@0
|
1174 if (params.type !== 'GET' && !options.emulateJSON) {
|
Daniel@0
|
1175 params.processData = false;
|
Daniel@0
|
1176 }
|
Daniel@0
|
1177
|
Daniel@0
|
1178 // If we're sending a `PATCH` request, and we're in an old Internet Explorer
|
Daniel@0
|
1179 // that still has ActiveX enabled by default, override jQuery to use that
|
Daniel@0
|
1180 // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
|
Daniel@0
|
1181 if (params.type === 'PATCH' && noXhrPatch) {
|
Daniel@0
|
1182 params.xhr = function() {
|
Daniel@0
|
1183 return new ActiveXObject("Microsoft.XMLHTTP");
|
Daniel@0
|
1184 };
|
Daniel@0
|
1185 }
|
Daniel@0
|
1186
|
Daniel@0
|
1187 // Make the request, allowing the user to override any Ajax options.
|
Daniel@0
|
1188 var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
|
Daniel@0
|
1189 model.trigger('request', model, xhr, options);
|
Daniel@0
|
1190 return xhr;
|
Daniel@0
|
1191 };
|
Daniel@0
|
1192
|
Daniel@0
|
1193 var noXhrPatch =
|
Daniel@0
|
1194 typeof window !== 'undefined' && !!window.ActiveXObject &&
|
Daniel@0
|
1195 !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
|
Daniel@0
|
1196
|
Daniel@0
|
1197 // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
|
Daniel@0
|
1198 var methodMap = {
|
Daniel@0
|
1199 'create': 'POST',
|
Daniel@0
|
1200 'update': 'PUT',
|
Daniel@0
|
1201 'patch': 'PATCH',
|
Daniel@0
|
1202 'delete': 'DELETE',
|
Daniel@0
|
1203 'read': 'GET'
|
Daniel@0
|
1204 };
|
Daniel@0
|
1205
|
Daniel@0
|
1206 // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
|
Daniel@0
|
1207 // Override this if you'd like to use a different library.
|
Daniel@0
|
1208 Backbone.ajax = function() {
|
Daniel@0
|
1209 return Backbone.$.ajax.apply(Backbone.$, arguments);
|
Daniel@0
|
1210 };
|
Daniel@0
|
1211
|
Daniel@0
|
1212 // Backbone.Router
|
Daniel@0
|
1213 // ---------------
|
Daniel@0
|
1214
|
Daniel@0
|
1215 // Routers map faux-URLs to actions, and fire events when routes are
|
Daniel@0
|
1216 // matched. Creating a new one sets its `routes` hash, if not set statically.
|
Daniel@0
|
1217 var Router = Backbone.Router = function(options) {
|
Daniel@0
|
1218 options || (options = {});
|
Daniel@0
|
1219 if (options.routes) this.routes = options.routes;
|
Daniel@0
|
1220 this._bindRoutes();
|
Daniel@0
|
1221 this.initialize.apply(this, arguments);
|
Daniel@0
|
1222 };
|
Daniel@0
|
1223
|
Daniel@0
|
1224 // Cached regular expressions for matching named param parts and splatted
|
Daniel@0
|
1225 // parts of route strings.
|
Daniel@0
|
1226 var optionalParam = /\((.*?)\)/g;
|
Daniel@0
|
1227 var namedParam = /(\(\?)?:\w+/g;
|
Daniel@0
|
1228 var splatParam = /\*\w+/g;
|
Daniel@0
|
1229 var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
|
Daniel@0
|
1230
|
Daniel@0
|
1231 // Set up all inheritable **Backbone.Router** properties and methods.
|
Daniel@0
|
1232 _.extend(Router.prototype, Events, {
|
Daniel@0
|
1233
|
Daniel@0
|
1234 // Initialize is an empty function by default. Override it with your own
|
Daniel@0
|
1235 // initialization logic.
|
Daniel@0
|
1236 initialize: function(){},
|
Daniel@0
|
1237
|
Daniel@0
|
1238 // Manually bind a single named route to a callback. For example:
|
Daniel@0
|
1239 //
|
Daniel@0
|
1240 // this.route('search/:query/p:num', 'search', function(query, num) {
|
Daniel@0
|
1241 // ...
|
Daniel@0
|
1242 // });
|
Daniel@0
|
1243 //
|
Daniel@0
|
1244 route: function(route, name, callback) {
|
Daniel@0
|
1245 if (!_.isRegExp(route)) route = this._routeToRegExp(route);
|
Daniel@0
|
1246 if (_.isFunction(name)) {
|
Daniel@0
|
1247 callback = name;
|
Daniel@0
|
1248 name = '';
|
Daniel@0
|
1249 }
|
Daniel@0
|
1250 if (!callback) callback = this[name];
|
Daniel@0
|
1251 var router = this;
|
Daniel@0
|
1252 Backbone.history.route(route, function(fragment) {
|
Daniel@0
|
1253 var args = router._extractParameters(route, fragment);
|
Daniel@0
|
1254 router.execute(callback, args);
|
Daniel@0
|
1255 router.trigger.apply(router, ['route:' + name].concat(args));
|
Daniel@0
|
1256 router.trigger('route', name, args);
|
Daniel@0
|
1257 Backbone.history.trigger('route', router, name, args);
|
Daniel@0
|
1258 });
|
Daniel@0
|
1259 return this;
|
Daniel@0
|
1260 },
|
Daniel@0
|
1261
|
Daniel@0
|
1262 // Execute a route handler with the provided parameters. This is an
|
Daniel@0
|
1263 // excellent place to do pre-route setup or post-route cleanup.
|
Daniel@0
|
1264 execute: function(callback, args) {
|
Daniel@0
|
1265 if (callback) callback.apply(this, args);
|
Daniel@0
|
1266 },
|
Daniel@0
|
1267
|
Daniel@0
|
1268 // Simple proxy to `Backbone.history` to save a fragment into the history.
|
Daniel@0
|
1269 navigate: function(fragment, options) {
|
Daniel@0
|
1270 Backbone.history.navigate(fragment, options);
|
Daniel@0
|
1271 return this;
|
Daniel@0
|
1272 },
|
Daniel@0
|
1273
|
Daniel@0
|
1274 // Bind all defined routes to `Backbone.history`. We have to reverse the
|
Daniel@0
|
1275 // order of the routes here to support behavior where the most general
|
Daniel@0
|
1276 // routes can be defined at the bottom of the route map.
|
Daniel@0
|
1277 _bindRoutes: function() {
|
Daniel@0
|
1278 if (!this.routes) return;
|
Daniel@0
|
1279 this.routes = _.result(this, 'routes');
|
Daniel@0
|
1280 var route, routes = _.keys(this.routes);
|
Daniel@0
|
1281 while ((route = routes.pop()) != null) {
|
Daniel@0
|
1282 this.route(route, this.routes[route]);
|
Daniel@0
|
1283 }
|
Daniel@0
|
1284 },
|
Daniel@0
|
1285
|
Daniel@0
|
1286 // Convert a route string into a regular expression, suitable for matching
|
Daniel@0
|
1287 // against the current location hash.
|
Daniel@0
|
1288 _routeToRegExp: function(route) {
|
Daniel@0
|
1289 route = route.replace(escapeRegExp, '\\$&')
|
Daniel@0
|
1290 .replace(optionalParam, '(?:$1)?')
|
Daniel@0
|
1291 .replace(namedParam, function(match, optional) {
|
Daniel@0
|
1292 return optional ? match : '([^/?]+)';
|
Daniel@0
|
1293 })
|
Daniel@0
|
1294 .replace(splatParam, '([^?]*?)');
|
Daniel@0
|
1295 return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
|
Daniel@0
|
1296 },
|
Daniel@0
|
1297
|
Daniel@0
|
1298 // Given a route, and a URL fragment that it matches, return the array of
|
Daniel@0
|
1299 // extracted decoded parameters. Empty or unmatched parameters will be
|
Daniel@0
|
1300 // treated as `null` to normalize cross-browser behavior.
|
Daniel@0
|
1301 _extractParameters: function(route, fragment) {
|
Daniel@0
|
1302 var params = route.exec(fragment).slice(1);
|
Daniel@0
|
1303 return _.map(params, function(param, i) {
|
Daniel@0
|
1304 // Don't decode the search params.
|
Daniel@0
|
1305 if (i === params.length - 1) return param || null;
|
Daniel@0
|
1306 return param ? decodeURIComponent(param) : null;
|
Daniel@0
|
1307 });
|
Daniel@0
|
1308 }
|
Daniel@0
|
1309
|
Daniel@0
|
1310 });
|
Daniel@0
|
1311
|
Daniel@0
|
1312 // Backbone.History
|
Daniel@0
|
1313 // ----------------
|
Daniel@0
|
1314
|
Daniel@0
|
1315 // Handles cross-browser history management, based on either
|
Daniel@0
|
1316 // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
|
Daniel@0
|
1317 // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
|
Daniel@0
|
1318 // and URL fragments. If the browser supports neither (old IE, natch),
|
Daniel@0
|
1319 // falls back to polling.
|
Daniel@0
|
1320 var History = Backbone.History = function() {
|
Daniel@0
|
1321 this.handlers = [];
|
Daniel@0
|
1322 _.bindAll(this, 'checkUrl');
|
Daniel@0
|
1323
|
Daniel@0
|
1324 // Ensure that `History` can be used outside of the browser.
|
Daniel@0
|
1325 if (typeof window !== 'undefined') {
|
Daniel@0
|
1326 this.location = window.location;
|
Daniel@0
|
1327 this.history = window.history;
|
Daniel@0
|
1328 }
|
Daniel@0
|
1329 };
|
Daniel@0
|
1330
|
Daniel@0
|
1331 // Cached regex for stripping a leading hash/slash and trailing space.
|
Daniel@0
|
1332 var routeStripper = /^[#\/]|\s+$/g;
|
Daniel@0
|
1333
|
Daniel@0
|
1334 // Cached regex for stripping leading and trailing slashes.
|
Daniel@0
|
1335 var rootStripper = /^\/+|\/+$/g;
|
Daniel@0
|
1336
|
Daniel@0
|
1337 // Cached regex for detecting MSIE.
|
Daniel@0
|
1338 var isExplorer = /msie [\w.]+/;
|
Daniel@0
|
1339
|
Daniel@0
|
1340 // Cached regex for removing a trailing slash.
|
Daniel@0
|
1341 var trailingSlash = /\/$/;
|
Daniel@0
|
1342
|
Daniel@0
|
1343 // Cached regex for stripping urls of hash.
|
Daniel@0
|
1344 var pathStripper = /#.*$/;
|
Daniel@0
|
1345
|
Daniel@0
|
1346 // Has the history handling already been started?
|
Daniel@0
|
1347 History.started = false;
|
Daniel@0
|
1348
|
Daniel@0
|
1349 // Set up all inheritable **Backbone.History** properties and methods.
|
Daniel@0
|
1350 _.extend(History.prototype, Events, {
|
Daniel@0
|
1351
|
Daniel@0
|
1352 // The default interval to poll for hash changes, if necessary, is
|
Daniel@0
|
1353 // twenty times a second.
|
Daniel@0
|
1354 interval: 50,
|
Daniel@0
|
1355
|
Daniel@0
|
1356 // Are we at the app root?
|
Daniel@0
|
1357 atRoot: function() {
|
Daniel@0
|
1358 return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root;
|
Daniel@0
|
1359 },
|
Daniel@0
|
1360
|
Daniel@0
|
1361 // Gets the true hash value. Cannot use location.hash directly due to bug
|
Daniel@0
|
1362 // in Firefox where location.hash will always be decoded.
|
Daniel@0
|
1363 getHash: function(window) {
|
Daniel@0
|
1364 var match = (window || this).location.href.match(/#(.*)$/);
|
Daniel@0
|
1365 return match ? match[1] : '';
|
Daniel@0
|
1366 },
|
Daniel@0
|
1367
|
Daniel@0
|
1368 // Get the cross-browser normalized URL fragment, either from the URL,
|
Daniel@0
|
1369 // the hash, or the override.
|
Daniel@0
|
1370 getFragment: function(fragment, forcePushState) {
|
Daniel@0
|
1371 if (fragment == null) {
|
Daniel@0
|
1372 if (this._hasPushState || !this._wantsHashChange || forcePushState) {
|
Daniel@0
|
1373 fragment = decodeURI(this.location.pathname + this.location.search);
|
Daniel@0
|
1374 var root = this.root.replace(trailingSlash, '');
|
Daniel@0
|
1375 if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
|
Daniel@0
|
1376 } else {
|
Daniel@0
|
1377 fragment = this.getHash();
|
Daniel@0
|
1378 }
|
Daniel@0
|
1379 }
|
Daniel@0
|
1380 return fragment.replace(routeStripper, '');
|
Daniel@0
|
1381 },
|
Daniel@0
|
1382
|
Daniel@0
|
1383 // Start the hash change handling, returning `true` if the current URL matches
|
Daniel@0
|
1384 // an existing route, and `false` otherwise.
|
Daniel@0
|
1385 start: function(options) {
|
Daniel@0
|
1386 if (History.started) throw new Error("Backbone.history has already been started");
|
Daniel@0
|
1387 History.started = true;
|
Daniel@0
|
1388
|
Daniel@0
|
1389 // Figure out the initial configuration. Do we need an iframe?
|
Daniel@0
|
1390 // Is pushState desired ... is it available?
|
Daniel@0
|
1391 this.options = _.extend({root: '/'}, this.options, options);
|
Daniel@0
|
1392 this.root = this.options.root;
|
Daniel@0
|
1393 this._wantsHashChange = this.options.hashChange !== false;
|
Daniel@0
|
1394 this._wantsPushState = !!this.options.pushState;
|
Daniel@0
|
1395 this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
|
Daniel@0
|
1396 var fragment = this.getFragment();
|
Daniel@0
|
1397 var docMode = document.documentMode;
|
Daniel@0
|
1398 var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
|
Daniel@0
|
1399
|
Daniel@0
|
1400 // Normalize root to always include a leading and trailing slash.
|
Daniel@0
|
1401 this.root = ('/' + this.root + '/').replace(rootStripper, '/');
|
Daniel@0
|
1402
|
Daniel@0
|
1403 if (oldIE && this._wantsHashChange) {
|
Daniel@0
|
1404 var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">');
|
Daniel@0
|
1405 this.iframe = frame.hide().appendTo('body')[0].contentWindow;
|
Daniel@0
|
1406 this.navigate(fragment);
|
Daniel@0
|
1407 }
|
Daniel@0
|
1408
|
Daniel@0
|
1409 // Depending on whether we're using pushState or hashes, and whether
|
Daniel@0
|
1410 // 'onhashchange' is supported, determine how we check the URL state.
|
Daniel@0
|
1411 if (this._hasPushState) {
|
Daniel@0
|
1412 Backbone.$(window).on('popstate', this.checkUrl);
|
Daniel@0
|
1413 } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
|
Daniel@0
|
1414 Backbone.$(window).on('hashchange', this.checkUrl);
|
Daniel@0
|
1415 } else if (this._wantsHashChange) {
|
Daniel@0
|
1416 this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
|
Daniel@0
|
1417 }
|
Daniel@0
|
1418
|
Daniel@0
|
1419 // Determine if we need to change the base url, for a pushState link
|
Daniel@0
|
1420 // opened by a non-pushState browser.
|
Daniel@0
|
1421 this.fragment = fragment;
|
Daniel@0
|
1422 var loc = this.location;
|
Daniel@0
|
1423
|
Daniel@0
|
1424 // Transition from hashChange to pushState or vice versa if both are
|
Daniel@0
|
1425 // requested.
|
Daniel@0
|
1426 if (this._wantsHashChange && this._wantsPushState) {
|
Daniel@0
|
1427
|
Daniel@0
|
1428 // If we've started off with a route from a `pushState`-enabled
|
Daniel@0
|
1429 // browser, but we're currently in a browser that doesn't support it...
|
Daniel@0
|
1430 if (!this._hasPushState && !this.atRoot()) {
|
Daniel@0
|
1431 this.fragment = this.getFragment(null, true);
|
Daniel@0
|
1432 this.location.replace(this.root + '#' + this.fragment);
|
Daniel@0
|
1433 // Return immediately as browser will do redirect to new url
|
Daniel@0
|
1434 return true;
|
Daniel@0
|
1435
|
Daniel@0
|
1436 // Or if we've started out with a hash-based route, but we're currently
|
Daniel@0
|
1437 // in a browser where it could be `pushState`-based instead...
|
Daniel@0
|
1438 } else if (this._hasPushState && this.atRoot() && loc.hash) {
|
Daniel@0
|
1439 this.fragment = this.getHash().replace(routeStripper, '');
|
Daniel@0
|
1440 this.history.replaceState({}, document.title, this.root + this.fragment);
|
Daniel@0
|
1441 }
|
Daniel@0
|
1442
|
Daniel@0
|
1443 }
|
Daniel@0
|
1444
|
Daniel@0
|
1445 if (!this.options.silent) return this.loadUrl();
|
Daniel@0
|
1446 },
|
Daniel@0
|
1447
|
Daniel@0
|
1448 // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
|
Daniel@0
|
1449 // but possibly useful for unit testing Routers.
|
Daniel@0
|
1450 stop: function() {
|
Daniel@0
|
1451 Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
|
Daniel@0
|
1452 if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
|
Daniel@0
|
1453 History.started = false;
|
Daniel@0
|
1454 },
|
Daniel@0
|
1455
|
Daniel@0
|
1456 // Add a route to be tested when the fragment changes. Routes added later
|
Daniel@0
|
1457 // may override previous routes.
|
Daniel@0
|
1458 route: function(route, callback) {
|
Daniel@0
|
1459 this.handlers.unshift({route: route, callback: callback});
|
Daniel@0
|
1460 },
|
Daniel@0
|
1461
|
Daniel@0
|
1462 // Checks the current URL to see if it has changed, and if it has,
|
Daniel@0
|
1463 // calls `loadUrl`, normalizing across the hidden iframe.
|
Daniel@0
|
1464 checkUrl: function(e) {
|
Daniel@0
|
1465 var current = this.getFragment();
|
Daniel@0
|
1466 if (current === this.fragment && this.iframe) {
|
Daniel@0
|
1467 current = this.getFragment(this.getHash(this.iframe));
|
Daniel@0
|
1468 }
|
Daniel@0
|
1469 if (current === this.fragment) return false;
|
Daniel@0
|
1470 if (this.iframe) this.navigate(current);
|
Daniel@0
|
1471 this.loadUrl();
|
Daniel@0
|
1472 },
|
Daniel@0
|
1473
|
Daniel@0
|
1474 // Attempt to load the current URL fragment. If a route succeeds with a
|
Daniel@0
|
1475 // match, returns `true`. If no defined routes matches the fragment,
|
Daniel@0
|
1476 // returns `false`.
|
Daniel@0
|
1477 loadUrl: function(fragment) {
|
Daniel@0
|
1478 fragment = this.fragment = this.getFragment(fragment);
|
Daniel@0
|
1479 return _.any(this.handlers, function(handler) {
|
Daniel@0
|
1480 if (handler.route.test(fragment)) {
|
Daniel@0
|
1481 handler.callback(fragment);
|
Daniel@0
|
1482 return true;
|
Daniel@0
|
1483 }
|
Daniel@0
|
1484 });
|
Daniel@0
|
1485 },
|
Daniel@0
|
1486
|
Daniel@0
|
1487 // Save a fragment into the hash history, or replace the URL state if the
|
Daniel@0
|
1488 // 'replace' option is passed. You are responsible for properly URL-encoding
|
Daniel@0
|
1489 // the fragment in advance.
|
Daniel@0
|
1490 //
|
Daniel@0
|
1491 // The options object can contain `trigger: true` if you wish to have the
|
Daniel@0
|
1492 // route callback be fired (not usually desirable), or `replace: true`, if
|
Daniel@0
|
1493 // you wish to modify the current URL without adding an entry to the history.
|
Daniel@0
|
1494 navigate: function(fragment, options) {
|
Daniel@0
|
1495 if (!History.started) return false;
|
Daniel@0
|
1496 if (!options || options === true) options = {trigger: !!options};
|
Daniel@0
|
1497
|
Daniel@0
|
1498 var url = this.root + (fragment = this.getFragment(fragment || ''));
|
Daniel@0
|
1499
|
Daniel@0
|
1500 // Strip the hash for matching.
|
Daniel@0
|
1501 fragment = fragment.replace(pathStripper, '');
|
Daniel@0
|
1502
|
Daniel@0
|
1503 if (this.fragment === fragment) return;
|
Daniel@0
|
1504 this.fragment = fragment;
|
Daniel@0
|
1505
|
Daniel@0
|
1506 // Don't include a trailing slash on the root.
|
Daniel@0
|
1507 if (fragment === '' && url !== '/') url = url.slice(0, -1);
|
Daniel@0
|
1508
|
Daniel@0
|
1509 // If pushState is available, we use it to set the fragment as a real URL.
|
Daniel@0
|
1510 if (this._hasPushState) {
|
Daniel@0
|
1511 this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
|
Daniel@0
|
1512
|
Daniel@0
|
1513 // If hash changes haven't been explicitly disabled, update the hash
|
Daniel@0
|
1514 // fragment to store history.
|
Daniel@0
|
1515 } else if (this._wantsHashChange) {
|
Daniel@0
|
1516 this._updateHash(this.location, fragment, options.replace);
|
Daniel@0
|
1517 if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
|
Daniel@0
|
1518 // Opening and closing the iframe tricks IE7 and earlier to push a
|
Daniel@0
|
1519 // history entry on hash-tag change. When replace is true, we don't
|
Daniel@0
|
1520 // want this.
|
Daniel@0
|
1521 if(!options.replace) this.iframe.document.open().close();
|
Daniel@0
|
1522 this._updateHash(this.iframe.location, fragment, options.replace);
|
Daniel@0
|
1523 }
|
Daniel@0
|
1524
|
Daniel@0
|
1525 // If you've told us that you explicitly don't want fallback hashchange-
|
Daniel@0
|
1526 // based history, then `navigate` becomes a page refresh.
|
Daniel@0
|
1527 } else {
|
Daniel@0
|
1528 return this.location.assign(url);
|
Daniel@0
|
1529 }
|
Daniel@0
|
1530 if (options.trigger) return this.loadUrl(fragment);
|
Daniel@0
|
1531 },
|
Daniel@0
|
1532
|
Daniel@0
|
1533 // Update the hash location, either replacing the current entry, or adding
|
Daniel@0
|
1534 // a new one to the browser history.
|
Daniel@0
|
1535 _updateHash: function(location, fragment, replace) {
|
Daniel@0
|
1536 if (replace) {
|
Daniel@0
|
1537 var href = location.href.replace(/(javascript:|#).*$/, '');
|
Daniel@0
|
1538 location.replace(href + '#' + fragment);
|
Daniel@0
|
1539 } else {
|
Daniel@0
|
1540 // Some browsers require that `hash` contains a leading #.
|
Daniel@0
|
1541 location.hash = '#' + fragment;
|
Daniel@0
|
1542 }
|
Daniel@0
|
1543 }
|
Daniel@0
|
1544
|
Daniel@0
|
1545 });
|
Daniel@0
|
1546
|
Daniel@0
|
1547 // Create the default Backbone.history.
|
Daniel@0
|
1548 Backbone.history = new History;
|
Daniel@0
|
1549
|
Daniel@0
|
1550 // Helpers
|
Daniel@0
|
1551 // -------
|
Daniel@0
|
1552
|
Daniel@0
|
1553 // Helper function to correctly set up the prototype chain, for subclasses.
|
Daniel@0
|
1554 // Similar to `goog.inherits`, but uses a hash of prototype properties and
|
Daniel@0
|
1555 // class properties to be extended.
|
Daniel@0
|
1556 var extend = function(protoProps, staticProps) {
|
Daniel@0
|
1557 var parent = this;
|
Daniel@0
|
1558 var child;
|
Daniel@0
|
1559
|
Daniel@0
|
1560 // The constructor function for the new subclass is either defined by you
|
Daniel@0
|
1561 // (the "constructor" property in your `extend` definition), or defaulted
|
Daniel@0
|
1562 // by us to simply call the parent's constructor.
|
Daniel@0
|
1563 if (protoProps && _.has(protoProps, 'constructor')) {
|
Daniel@0
|
1564 child = protoProps.constructor;
|
Daniel@0
|
1565 } else {
|
Daniel@0
|
1566 child = function(){ return parent.apply(this, arguments); };
|
Daniel@0
|
1567 }
|
Daniel@0
|
1568
|
Daniel@0
|
1569 // Add static properties to the constructor function, if supplied.
|
Daniel@0
|
1570 _.extend(child, parent, staticProps);
|
Daniel@0
|
1571
|
Daniel@0
|
1572 // Set the prototype chain to inherit from `parent`, without calling
|
Daniel@0
|
1573 // `parent`'s constructor function.
|
Daniel@0
|
1574 var Surrogate = function(){ this.constructor = child; };
|
Daniel@0
|
1575 Surrogate.prototype = parent.prototype;
|
Daniel@0
|
1576 child.prototype = new Surrogate;
|
Daniel@0
|
1577
|
Daniel@0
|
1578 // Add prototype properties (instance properties) to the subclass,
|
Daniel@0
|
1579 // if supplied.
|
Daniel@0
|
1580 if (protoProps) _.extend(child.prototype, protoProps);
|
Daniel@0
|
1581
|
Daniel@0
|
1582 // Set a convenience property in case the parent's prototype is needed
|
Daniel@0
|
1583 // later.
|
Daniel@0
|
1584 child.__super__ = parent.prototype;
|
Daniel@0
|
1585
|
Daniel@0
|
1586 return child;
|
Daniel@0
|
1587 };
|
Daniel@0
|
1588
|
Daniel@0
|
1589 // Set up inheritance for the model, collection, router, view and history.
|
Daniel@0
|
1590 Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
|
Daniel@0
|
1591
|
Daniel@0
|
1592 // Throw an error when a URL is needed, and none is supplied.
|
Daniel@0
|
1593 var urlError = function() {
|
Daniel@0
|
1594 throw new Error('A "url" property or function must be specified');
|
Daniel@0
|
1595 };
|
Daniel@0
|
1596
|
Daniel@0
|
1597 // Wrap an optional error callback with a fallback error event.
|
Daniel@0
|
1598 var wrapError = function(model, options) {
|
Daniel@0
|
1599 var error = options.error;
|
Daniel@0
|
1600 options.error = function(resp) {
|
Daniel@0
|
1601 if (error) error(model, resp, options);
|
Daniel@0
|
1602 model.trigger('error', model, resp, options);
|
Daniel@0
|
1603 };
|
Daniel@0
|
1604 };
|
Daniel@0
|
1605
|
Daniel@0
|
1606 return Backbone;
|
Daniel@0
|
1607
|
Daniel@0
|
1608 }));
|