├── .npmignore
├── LICENSE
├── README.md
├── backbone.analytics.js
├── package.json
└── tests
├── backbone.analytics.test.js
├── test.html
└── vendor
├── backbone.js
├── jquery.js
├── qunit.css
├── qunit.js
└── underscore.js
/.npmignore:
--------------------------------------------------------------------------------
1 | tests
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (C) 2013 by Kendall Buchanan
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Backbone.Analytics
2 |
3 | A drop-in plugin that integrates Google's `trackEvent` directly into Backbone's `navigate` function. Works best with `pushState` set to `true`. If `pushState` is turned off, it's possible Google will register visits twice on page load. You can mitigate that by removing the `trackEvent` from the Google code in your site.
4 |
5 | ### Dependencies
6 |
7 | * [Backbone.js](http://documentcloud.github.com/backbone/) (Tested in 1.0)
8 |
9 | ## Traditional Install
10 |
11 | Add the [asynchronous Google Analytics code](http://code.google.com/apis/analytics/docs/tracking/asyncTracking.html) to your site.
12 |
13 | Add these dependencies to your site's `
`, **in order**:
14 |
15 | ```
16 |
17 |
18 |
19 | ```
20 |
21 | ## NPM Install
22 |
23 | Install [NPM module](https://www.npmjs.com/package/backbone.analytics):
24 |
25 | ```
26 | npm install backbone.analytics --save
27 | ```
28 |
29 | ## Usage
30 | Anywhere you call your router's navigate method with the trigger option set to true Backbone.Analytics will call `_gaq.push(['_trackPageview', '/some-page'])` after completing the Backbone route. This pushes the route to the Google Analytics tracking queue. Once this queue is processed by the Google Analytics script your urls will be tracked to the Google Analytics server.
31 |
32 | ```javascript
33 | var TestRouter = Backbone.Router.extend({
34 | routes: {
35 | 'some-page': 'somePage'
36 | },
37 |
38 | somePage: function() {
39 | // Perform your route based logic, e.g. Replace the current view with a different one.
40 | return false;
41 | }
42 | });
43 |
44 | var router = new TestRouter();
45 | Backbone.history.start();
46 | ```
47 |
48 | Somewhere else in your application, change the view by doing:
49 | ```javascript
50 | router.navigate('some-page', { trigger: true });
51 | ```
52 |
53 | Anywhere in your application where you want to update the URL but do **not** trigger the associated route, you will still need to manually track the action.
54 |
--------------------------------------------------------------------------------
/backbone.analytics.js:
--------------------------------------------------------------------------------
1 | (function(factory) {
2 |
3 | 'use strict';
4 |
5 | if (typeof define === 'function' && define.amd) {
6 | define(['backbone'], factory);
7 | } else if (typeof exports === 'object') {
8 | module.exports = factory(require('backbone'));
9 | } else {
10 | factory(window.Backbone);
11 | }
12 | })(function(Backbone) {
13 |
14 | 'use strict';
15 |
16 | var loadUrl = Backbone.History.prototype.loadUrl;
17 |
18 | Backbone.History.prototype.loadUrl = function(fragmentOverride) {
19 | var matched = loadUrl.apply(this, arguments),
20 | gaFragment = this.fragment;
21 |
22 | if (!this.options.silent) {
23 | this.options.silent = true;
24 | return matched;
25 | }
26 |
27 | if (!/^\//.test(gaFragment)) {
28 | gaFragment = '/' + gaFragment;
29 | }
30 |
31 | // legacy version
32 | if (typeof window._gaq !== "undefined") {
33 | window._gaq.push(['_trackPageview', gaFragment]);
34 | }
35 |
36 | // Analytics.js
37 | var ga;
38 | if (window.GoogleAnalyticsObject && window.GoogleAnalyticsObject !== 'ga') {
39 | ga = window.GoogleAnalyticsObject;
40 | } else {
41 | ga = window.ga;
42 | }
43 |
44 | if (typeof ga !== 'undefined') {
45 | ga('set', 'page', gaFragment);
46 | ga('send', 'pageview');
47 | }
48 | return matched;
49 | };
50 |
51 | });
52 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "backbone.analytics",
3 | "version": "1.0.2",
4 | "description": "A drop-in plugin that integrates Google's `trackEvent` directly into Backbone's `navigate` function.",
5 | "keywords": [
6 | "backbone",
7 | "google",
8 | "analytics",
9 | "pageviews"
10 | ],
11 | "homepage": "https://github.com/kendagriff/backbone.analytics",
12 | "bugs": {
13 | "url": "https://github.com/kendagriff/backbone.analytics/issues"
14 | },
15 | "author": {
16 | "name": "Kendall Buchanan",
17 | "url": "https://github.com/kendagriff"
18 | },
19 | "contributors": [
20 | {
21 | "name": "Wills Bithrey",
22 | "email": "wills@willsbithrey.com",
23 | "url": "https://github.com/WillsB3"
24 | },
25 | {
26 | "name": "Paul English"
27 | },
28 | {
29 | "name": "Kendall Buchanan",
30 | "url": "https://github.com/kendagriff"
31 | },
32 | {
33 | "name": "Makis Tracend",
34 | "email": "makis.tracend@gmail.com",
35 | "url": "https://github.com/tracend"
36 | }
37 | ],
38 | "main": "backbone.analytics.js",
39 | "repository": {
40 | "type": "git",
41 | "url": "git://github.com/kendagriff/backbone.analytics.git"
42 | },
43 | "scripts": {
44 | "test": "echo \"Error: no test specified\" && exit 1"
45 | },
46 | "licenses": [
47 | {
48 | "type": "MIT",
49 | "url": "https://github.com/kendagriff/backbone.analytics/blob/master/LICENSE"
50 | }
51 | ],
52 | "devDependencies": {
53 | "backbone": "~1.0.0"
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/tests/backbone.analytics.test.js:
--------------------------------------------------------------------------------
1 | var TestRouter = Backbone.Router.extend({
2 | routes: {
3 | 'some-page': 'somePage'
4 | },
5 |
6 | somePage: function() {
7 | // Pretend we are doing something
8 | return false;
9 | }
10 | });
11 |
12 | $(document).ready(function() {
13 | // Setup
14 | module('core', {
15 | setup: function() {
16 | window._gaq = [];
17 | this.router = new TestRouter();
18 | Backbone.history.start();
19 | }
20 | });
21 |
22 | // Tests
23 | test("Visit URL, trigger Google's trackEvent", function() {
24 | // Check that the initial route was tracked
25 | equal(_gaq.length, 1);
26 | equal(_gaq[0][0], '_trackPageview');
27 | equal(_gaq[0][1], '/');
28 |
29 | // Check that calling a route works
30 | this.router.navigate('some-page', { trigger: true });
31 | equal(_gaq.length, 2);
32 | equal(_gaq[1][0], '_trackPageview');
33 | equal(_gaq[1][1], '/some-page');
34 | });
35 |
36 | });
37 |
--------------------------------------------------------------------------------
/tests/test.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Backbone.Analytics Test Suite
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/tests/vendor/backbone.js:
--------------------------------------------------------------------------------
1 | // Backbone.js 1.0.0
2 |
3 | // (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.
4 | // (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
5 | // Backbone may be freely distributed under the MIT license.
6 | // For all details and documentation:
7 | // http://backbonejs.org
8 |
9 | (function(){
10 |
11 | // Initial Setup
12 | // -------------
13 |
14 | // Save a reference to the global object (`window` in the browser, `exports`
15 | // on the server).
16 | var root = this;
17 |
18 | // Save the previous value of the `Backbone` variable, so that it can be
19 | // restored later on, if `noConflict` is used.
20 | var previousBackbone = root.Backbone;
21 |
22 | // Create local references to array methods we'll want to use later.
23 | var array = [];
24 | var push = array.push;
25 | var slice = array.slice;
26 | var splice = array.splice;
27 |
28 | // The top-level namespace. All public Backbone classes and modules will
29 | // be attached to this. Exported for both the browser and the server.
30 | var Backbone;
31 | if (typeof exports !== 'undefined') {
32 | Backbone = exports;
33 | } else {
34 | Backbone = root.Backbone = {};
35 | }
36 |
37 | // Current version of the library. Keep in sync with `package.json`.
38 | Backbone.VERSION = '1.0.0';
39 |
40 | // Require Underscore, if we're on the server, and it's not already present.
41 | var _ = root._;
42 | if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
43 |
44 | // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
45 | // the `$` variable.
46 | Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
47 |
48 | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
49 | // to its previous owner. Returns a reference to this Backbone object.
50 | Backbone.noConflict = function() {
51 | root.Backbone = previousBackbone;
52 | return this;
53 | };
54 |
55 | // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
56 | // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
57 | // set a `X-Http-Method-Override` header.
58 | Backbone.emulateHTTP = false;
59 |
60 | // Turn on `emulateJSON` to support legacy servers that can't deal with direct
61 | // `application/json` requests ... will encode the body as
62 | // `application/x-www-form-urlencoded` instead and will send the model in a
63 | // form param named `model`.
64 | Backbone.emulateJSON = false;
65 |
66 | // Backbone.Events
67 | // ---------------
68 |
69 | // A module that can be mixed in to *any object* in order to provide it with
70 | // custom events. You may bind with `on` or remove with `off` callback
71 | // functions to an event; `trigger`-ing an event fires all callbacks in
72 | // succession.
73 | //
74 | // var object = {};
75 | // _.extend(object, Backbone.Events);
76 | // object.on('expand', function(){ alert('expanded'); });
77 | // object.trigger('expand');
78 | //
79 | var Events = Backbone.Events = {
80 |
81 | // Bind an event to a `callback` function. Passing `"all"` will bind
82 | // the callback to all events fired.
83 | on: function(name, callback, context) {
84 | if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
85 | this._events || (this._events = {});
86 | var events = this._events[name] || (this._events[name] = []);
87 | events.push({callback: callback, context: context, ctx: context || this});
88 | return this;
89 | },
90 |
91 | // Bind an event to only be triggered a single time. After the first time
92 | // the callback is invoked, it will be removed.
93 | once: function(name, callback, context) {
94 | if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
95 | var self = this;
96 | var once = _.once(function() {
97 | self.off(name, once);
98 | callback.apply(this, arguments);
99 | });
100 | once._callback = callback;
101 | return this.on(name, once, context);
102 | },
103 |
104 | // Remove one or many callbacks. If `context` is null, removes all
105 | // callbacks with that function. If `callback` is null, removes all
106 | // callbacks for the event. If `name` is null, removes all bound
107 | // callbacks for all events.
108 | off: function(name, callback, context) {
109 | var retain, ev, events, names, i, l, j, k;
110 | if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
111 | if (!name && !callback && !context) {
112 | this._events = {};
113 | return this;
114 | }
115 |
116 | names = name ? [name] : _.keys(this._events);
117 | for (i = 0, l = names.length; i < l; i++) {
118 | name = names[i];
119 | if (events = this._events[name]) {
120 | this._events[name] = retain = [];
121 | if (callback || context) {
122 | for (j = 0, k = events.length; j < k; j++) {
123 | ev = events[j];
124 | if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
125 | (context && context !== ev.context)) {
126 | retain.push(ev);
127 | }
128 | }
129 | }
130 | if (!retain.length) delete this._events[name];
131 | }
132 | }
133 |
134 | return this;
135 | },
136 |
137 | // Trigger one or many events, firing all bound callbacks. Callbacks are
138 | // passed the same arguments as `trigger` is, apart from the event name
139 | // (unless you're listening on `"all"`, which will cause your callback to
140 | // receive the true name of the event as the first argument).
141 | trigger: function(name) {
142 | if (!this._events) return this;
143 | var args = slice.call(arguments, 1);
144 | if (!eventsApi(this, 'trigger', name, args)) return this;
145 | var events = this._events[name];
146 | var allEvents = this._events.all;
147 | if (events) triggerEvents(events, args);
148 | if (allEvents) triggerEvents(allEvents, arguments);
149 | return this;
150 | },
151 |
152 | // Tell this object to stop listening to either specific events ... or
153 | // to every object it's currently listening to.
154 | stopListening: function(obj, name, callback) {
155 | var listeners = this._listeners;
156 | if (!listeners) return this;
157 | var deleteListener = !name && !callback;
158 | if (typeof name === 'object') callback = this;
159 | if (obj) (listeners = {})[obj._listenerId] = obj;
160 | for (var id in listeners) {
161 | listeners[id].off(name, callback, this);
162 | if (deleteListener) delete this._listeners[id];
163 | }
164 | return this;
165 | }
166 |
167 | };
168 |
169 | // Regular expression used to split event strings.
170 | var eventSplitter = /\s+/;
171 |
172 | // Implement fancy features of the Events API such as multiple event
173 | // names `"change blur"` and jQuery-style event maps `{change: action}`
174 | // in terms of the existing API.
175 | var eventsApi = function(obj, action, name, rest) {
176 | if (!name) return true;
177 |
178 | // Handle event maps.
179 | if (typeof name === 'object') {
180 | for (var key in name) {
181 | obj[action].apply(obj, [key, name[key]].concat(rest));
182 | }
183 | return false;
184 | }
185 |
186 | // Handle space separated event names.
187 | if (eventSplitter.test(name)) {
188 | var names = name.split(eventSplitter);
189 | for (var i = 0, l = names.length; i < l; i++) {
190 | obj[action].apply(obj, [names[i]].concat(rest));
191 | }
192 | return false;
193 | }
194 |
195 | return true;
196 | };
197 |
198 | // A difficult-to-believe, but optimized internal dispatch function for
199 | // triggering events. Tries to keep the usual cases speedy (most internal
200 | // Backbone events have 3 arguments).
201 | var triggerEvents = function(events, args) {
202 | var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
203 | switch (args.length) {
204 | case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
205 | case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
206 | case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
207 | case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
208 | default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
209 | }
210 | };
211 |
212 | var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
213 |
214 | // Inversion-of-control versions of `on` and `once`. Tell *this* object to
215 | // listen to an event in another object ... keeping track of what it's
216 | // listening to.
217 | _.each(listenMethods, function(implementation, method) {
218 | Events[method] = function(obj, name, callback) {
219 | var listeners = this._listeners || (this._listeners = {});
220 | var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
221 | listeners[id] = obj;
222 | if (typeof name === 'object') callback = this;
223 | obj[implementation](name, callback, this);
224 | return this;
225 | };
226 | });
227 |
228 | // Aliases for backwards compatibility.
229 | Events.bind = Events.on;
230 | Events.unbind = Events.off;
231 |
232 | // Allow the `Backbone` object to serve as a global event bus, for folks who
233 | // want global "pubsub" in a convenient place.
234 | _.extend(Backbone, Events);
235 |
236 | // Backbone.Model
237 | // --------------
238 |
239 | // Backbone **Models** are the basic data object in the framework --
240 | // frequently representing a row in a table in a database on your server.
241 | // A discrete chunk of data and a bunch of useful, related methods for
242 | // performing computations and transformations on that data.
243 |
244 | // Create a new model with the specified attributes. A client id (`cid`)
245 | // is automatically generated and assigned for you.
246 | var Model = Backbone.Model = function(attributes, options) {
247 | var defaults;
248 | var attrs = attributes || {};
249 | options || (options = {});
250 | this.cid = _.uniqueId('c');
251 | this.attributes = {};
252 | if (options.collection) this.collection = options.collection;
253 | if (options.parse) attrs = this.parse(attrs, options) || {};
254 | options._attrs || (options._attrs = attrs);
255 | if (defaults = _.result(this, 'defaults')) {
256 | attrs = _.defaults({}, attrs, defaults);
257 | }
258 | this.set(attrs, options);
259 | this.changed = {};
260 | this.initialize.apply(this, arguments);
261 | };
262 |
263 | // Attach all inheritable methods to the Model prototype.
264 | _.extend(Model.prototype, Events, {
265 |
266 | // A hash of attributes whose current and previous value differ.
267 | changed: null,
268 |
269 | // The value returned during the last failed validation.
270 | validationError: null,
271 |
272 | // The default name for the JSON `id` attribute is `"id"`. MongoDB and
273 | // CouchDB users may want to set this to `"_id"`.
274 | idAttribute: 'id',
275 |
276 | // Initialize is an empty function by default. Override it with your own
277 | // initialization logic.
278 | initialize: function(){},
279 |
280 | // Return a copy of the model's `attributes` object.
281 | toJSON: function(options) {
282 | return _.clone(this.attributes);
283 | },
284 |
285 | // Proxy `Backbone.sync` by default -- but override this if you need
286 | // custom syncing semantics for *this* particular model.
287 | sync: function() {
288 | return Backbone.sync.apply(this, arguments);
289 | },
290 |
291 | // Get the value of an attribute.
292 | get: function(attr) {
293 | return this.attributes[attr];
294 | },
295 |
296 | // Get the HTML-escaped value of an attribute.
297 | escape: function(attr) {
298 | return _.escape(this.get(attr));
299 | },
300 |
301 | // Returns `true` if the attribute contains a value that is not null
302 | // or undefined.
303 | has: function(attr) {
304 | return this.get(attr) != null;
305 | },
306 |
307 | // Set a hash of model attributes on the object, firing `"change"`. This is
308 | // the core primitive operation of a model, updating the data and notifying
309 | // anyone who needs to know about the change in state. The heart of the beast.
310 | set: function(key, val, options) {
311 | var attr, attrs, unset, changes, silent, changing, prev, current;
312 | if (key == null) return this;
313 |
314 | // Handle both `"key", value` and `{key: value}` -style arguments.
315 | if (typeof key === 'object') {
316 | attrs = key;
317 | options = val;
318 | } else {
319 | (attrs = {})[key] = val;
320 | }
321 |
322 | options || (options = {});
323 |
324 | // Run validation.
325 | if (!this._validate(attrs, options)) return false;
326 |
327 | // Extract attributes and options.
328 | unset = options.unset;
329 | silent = options.silent;
330 | changes = [];
331 | changing = this._changing;
332 | this._changing = true;
333 |
334 | if (!changing) {
335 | this._previousAttributes = _.clone(this.attributes);
336 | this.changed = {};
337 | }
338 | current = this.attributes, prev = this._previousAttributes;
339 |
340 | // Check for changes of `id`.
341 | if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
342 |
343 | // For each `set` attribute, update or delete the current value.
344 | for (attr in attrs) {
345 | val = attrs[attr];
346 | if (!_.isEqual(current[attr], val)) changes.push(attr);
347 | if (!_.isEqual(prev[attr], val)) {
348 | this.changed[attr] = val;
349 | } else {
350 | delete this.changed[attr];
351 | }
352 | unset ? delete current[attr] : current[attr] = val;
353 | }
354 |
355 | // Trigger all relevant attribute changes.
356 | if (!silent) {
357 | if (changes.length) this._pending = true;
358 | for (var i = 0, l = changes.length; i < l; i++) {
359 | this.trigger('change:' + changes[i], this, current[changes[i]], options);
360 | }
361 | }
362 |
363 | // You might be wondering why there's a `while` loop here. Changes can
364 | // be recursively nested within `"change"` events.
365 | if (changing) return this;
366 | if (!silent) {
367 | while (this._pending) {
368 | this._pending = false;
369 | this.trigger('change', this, options);
370 | }
371 | }
372 | this._pending = false;
373 | this._changing = false;
374 | return this;
375 | },
376 |
377 | // Remove an attribute from the model, firing `"change"`. `unset` is a noop
378 | // if the attribute doesn't exist.
379 | unset: function(attr, options) {
380 | return this.set(attr, void 0, _.extend({}, options, {unset: true}));
381 | },
382 |
383 | // Clear all attributes on the model, firing `"change"`.
384 | clear: function(options) {
385 | var attrs = {};
386 | for (var key in this.attributes) attrs[key] = void 0;
387 | return this.set(attrs, _.extend({}, options, {unset: true}));
388 | },
389 |
390 | // Determine if the model has changed since the last `"change"` event.
391 | // If you specify an attribute name, determine if that attribute has changed.
392 | hasChanged: function(attr) {
393 | if (attr == null) return !_.isEmpty(this.changed);
394 | return _.has(this.changed, attr);
395 | },
396 |
397 | // Return an object containing all the attributes that have changed, or
398 | // false if there are no changed attributes. Useful for determining what
399 | // parts of a view need to be updated and/or what attributes need to be
400 | // persisted to the server. Unset attributes will be set to undefined.
401 | // You can also pass an attributes object to diff against the model,
402 | // determining if there *would be* a change.
403 | changedAttributes: function(diff) {
404 | if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
405 | var val, changed = false;
406 | var old = this._changing ? this._previousAttributes : this.attributes;
407 | for (var attr in diff) {
408 | if (_.isEqual(old[attr], (val = diff[attr]))) continue;
409 | (changed || (changed = {}))[attr] = val;
410 | }
411 | return changed;
412 | },
413 |
414 | // Get the previous value of an attribute, recorded at the time the last
415 | // `"change"` event was fired.
416 | previous: function(attr) {
417 | if (attr == null || !this._previousAttributes) return null;
418 | return this._previousAttributes[attr];
419 | },
420 |
421 | // Get all of the attributes of the model at the time of the previous
422 | // `"change"` event.
423 | previousAttributes: function() {
424 | return _.clone(this._previousAttributes);
425 | },
426 |
427 | // Fetch the model from the server. If the server's representation of the
428 | // model differs from its current attributes, they will be overridden,
429 | // triggering a `"change"` event.
430 | fetch: function(options) {
431 | options = options ? _.clone(options) : {};
432 | if (options.parse === void 0) options.parse = true;
433 | var model = this;
434 | var success = options.success;
435 | options.success = function(resp) {
436 | if (!model.set(model.parse(resp, options), options)) return false;
437 | if (success) success(model, resp, options);
438 | model.trigger('sync', model, resp, options);
439 | };
440 | wrapError(this, options);
441 | return this.sync('read', this, options);
442 | },
443 |
444 | // Set a hash of model attributes, and sync the model to the server.
445 | // If the server returns an attributes hash that differs, the model's
446 | // state will be `set` again.
447 | save: function(key, val, options) {
448 | var attrs, method, xhr, attributes = this.attributes;
449 |
450 | // Handle both `"key", value` and `{key: value}` -style arguments.
451 | if (key == null || typeof key === 'object') {
452 | attrs = key;
453 | options = val;
454 | } else {
455 | (attrs = {})[key] = val;
456 | }
457 |
458 | options = _.extend({validate: true}, options);
459 |
460 | // If we're not waiting and attributes exist, save acts as
461 | // `set(attr).save(null, opts)` with validation. Otherwise, check if
462 | // the model will be valid when the attributes, if any, are set.
463 | if (attrs && !options.wait) {
464 | if (!this.set(attrs, options)) return false;
465 | } else {
466 | if (!this._validate(attrs, options)) return false;
467 | }
468 |
469 | // Set temporary attributes if `{wait: true}`.
470 | if (attrs && options.wait) {
471 | this.attributes = _.extend({}, attributes, attrs);
472 | }
473 |
474 | // After a successful server-side save, the client is (optionally)
475 | // updated with the server-side state.
476 | if (options.parse === void 0) options.parse = true;
477 | var model = this;
478 | var success = options.success;
479 | options.success = function(resp) {
480 | // Ensure attributes are restored during synchronous saves.
481 | model.attributes = attributes;
482 | var serverAttrs = model.parse(resp, options);
483 | if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
484 | if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
485 | return false;
486 | }
487 | if (success) success(model, resp, options);
488 | model.trigger('sync', model, resp, options);
489 | };
490 | wrapError(this, options);
491 |
492 | method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
493 | if (method === 'patch') options.attrs = attrs;
494 | xhr = this.sync(method, this, options);
495 |
496 | // Restore attributes.
497 | if (attrs && options.wait) this.attributes = attributes;
498 |
499 | return xhr;
500 | },
501 |
502 | // Destroy this model on the server if it was already persisted.
503 | // Optimistically removes the model from its collection, if it has one.
504 | // If `wait: true` is passed, waits for the server to respond before removal.
505 | destroy: function(options) {
506 | options = options ? _.clone(options) : {};
507 | var model = this;
508 | var success = options.success;
509 |
510 | var destroy = function() {
511 | model.trigger('destroy', model, model.collection, options);
512 | };
513 |
514 | options.success = function(resp) {
515 | if (options.wait || model.isNew()) destroy();
516 | if (success) success(model, resp, options);
517 | if (!model.isNew()) model.trigger('sync', model, resp, options);
518 | };
519 |
520 | if (this.isNew()) {
521 | options.success();
522 | return false;
523 | }
524 | wrapError(this, options);
525 |
526 | var xhr = this.sync('delete', this, options);
527 | if (!options.wait) destroy();
528 | return xhr;
529 | },
530 |
531 | // Default URL for the model's representation on the server -- if you're
532 | // using Backbone's restful methods, override this to change the endpoint
533 | // that will be called.
534 | url: function() {
535 | var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
536 | if (this.isNew()) return base;
537 | return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
538 | },
539 |
540 | // **parse** converts a response into the hash of attributes to be `set` on
541 | // the model. The default implementation is just to pass the response along.
542 | parse: function(resp, options) {
543 | return resp;
544 | },
545 |
546 | // Create a new model with identical attributes to this one.
547 | clone: function() {
548 | return new this.constructor(this.attributes);
549 | },
550 |
551 | // A model is new if it has never been saved to the server, and lacks an id.
552 | isNew: function() {
553 | return this.id == null;
554 | },
555 |
556 | // Check if the model is currently in a valid state.
557 | isValid: function(options) {
558 | return this._validate({}, _.extend(options || {}, { validate: true }));
559 | },
560 |
561 | // Run validation against the next complete set of model attributes,
562 | // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
563 | _validate: function(attrs, options) {
564 | if (!options.validate || !this.validate) return true;
565 | attrs = _.extend({}, this.attributes, attrs);
566 | var error = this.validationError = this.validate(attrs, options) || null;
567 | if (!error) return true;
568 | this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error}));
569 | return false;
570 | }
571 |
572 | });
573 |
574 | // Underscore methods that we want to implement on the Model.
575 | var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
576 |
577 | // Mix in each Underscore method as a proxy to `Model#attributes`.
578 | _.each(modelMethods, function(method) {
579 | Model.prototype[method] = function() {
580 | var args = slice.call(arguments);
581 | args.unshift(this.attributes);
582 | return _[method].apply(_, args);
583 | };
584 | });
585 |
586 | // Backbone.Collection
587 | // -------------------
588 |
589 | // If models tend to represent a single row of data, a Backbone Collection is
590 | // more analagous to a table full of data ... or a small slice or page of that
591 | // table, or a collection of rows that belong together for a particular reason
592 | // -- all of the messages in this particular folder, all of the documents
593 | // belonging to this particular author, and so on. Collections maintain
594 | // indexes of their models, both in order, and for lookup by `id`.
595 |
596 | // Create a new **Collection**, perhaps to contain a specific type of `model`.
597 | // If a `comparator` is specified, the Collection will maintain
598 | // its models in sort order, as they're added and removed.
599 | var Collection = Backbone.Collection = function(models, options) {
600 | options || (options = {});
601 | if (options.model) this.model = options.model;
602 | if (options.comparator !== void 0) this.comparator = options.comparator;
603 | this._reset();
604 | this.initialize.apply(this, arguments);
605 | if (models) this.reset(models, _.extend({silent: true}, options));
606 | };
607 |
608 | // Default options for `Collection#set`.
609 | var setOptions = {add: true, remove: true, merge: true};
610 | var addOptions = {add: true, merge: false, remove: false};
611 |
612 | // Define the Collection's inheritable methods.
613 | _.extend(Collection.prototype, Events, {
614 |
615 | // The default model for a collection is just a **Backbone.Model**.
616 | // This should be overridden in most cases.
617 | model: Model,
618 |
619 | // Initialize is an empty function by default. Override it with your own
620 | // initialization logic.
621 | initialize: function(){},
622 |
623 | // The JSON representation of a Collection is an array of the
624 | // models' attributes.
625 | toJSON: function(options) {
626 | return this.map(function(model){ return model.toJSON(options); });
627 | },
628 |
629 | // Proxy `Backbone.sync` by default.
630 | sync: function() {
631 | return Backbone.sync.apply(this, arguments);
632 | },
633 |
634 | // Add a model, or list of models to the set.
635 | add: function(models, options) {
636 | return this.set(models, _.defaults(options || {}, addOptions));
637 | },
638 |
639 | // Remove a model, or a list of models from the set.
640 | remove: function(models, options) {
641 | models = _.isArray(models) ? models.slice() : [models];
642 | options || (options = {});
643 | var i, l, index, model;
644 | for (i = 0, l = models.length; i < l; i++) {
645 | model = this.get(models[i]);
646 | if (!model) continue;
647 | delete this._byId[model.id];
648 | delete this._byId[model.cid];
649 | index = this.indexOf(model);
650 | this.models.splice(index, 1);
651 | this.length--;
652 | if (!options.silent) {
653 | options.index = index;
654 | model.trigger('remove', model, this, options);
655 | }
656 | this._removeReference(model);
657 | }
658 | return this;
659 | },
660 |
661 | // Update a collection by `set`-ing a new list of models, adding new ones,
662 | // removing models that are no longer present, and merging models that
663 | // already exist in the collection, as necessary. Similar to **Model#set**,
664 | // the core operation for updating the data contained by the collection.
665 | set: function(models, options) {
666 | options = _.defaults(options || {}, setOptions);
667 | if (options.parse) models = this.parse(models, options);
668 | if (!_.isArray(models)) models = models ? [models] : [];
669 | var i, l, model, attrs, existing, sort;
670 | var at = options.at;
671 | var sortable = this.comparator && (at == null) && options.sort !== false;
672 | var sortAttr = _.isString(this.comparator) ? this.comparator : null;
673 | var toAdd = [], toRemove = [], modelMap = {};
674 | var add = options.add, merge = options.merge, remove = options.remove;
675 | var order = !sortable && add && remove ? [] : false;
676 |
677 | // Turn bare objects into model references, and prevent invalid models
678 | // from being added.
679 | for (i = 0, l = models.length; i < l; i++) {
680 | if (!(model = this._prepareModel(attrs = models[i], options))) continue;
681 |
682 | // If a duplicate is found, prevent it from being added and
683 | // optionally merge it into the existing model.
684 | if (existing = this.get(model)) {
685 | if (remove) modelMap[existing.cid] = true;
686 | if (merge) {
687 | attrs = attrs === model ? model.attributes : options._attrs;
688 | delete options._attrs;
689 | existing.set(attrs, options);
690 | if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
691 | }
692 |
693 | // This is a new model, push it to the `toAdd` list.
694 | } else if (add) {
695 | toAdd.push(model);
696 |
697 | // Listen to added models' events, and index models for lookup by
698 | // `id` and by `cid`.
699 | model.on('all', this._onModelEvent, this);
700 | this._byId[model.cid] = model;
701 | if (model.id != null) this._byId[model.id] = model;
702 | }
703 | if (order) order.push(existing || model);
704 | }
705 |
706 | // Remove nonexistent models if appropriate.
707 | if (remove) {
708 | for (i = 0, l = this.length; i < l; ++i) {
709 | if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
710 | }
711 | if (toRemove.length) this.remove(toRemove, options);
712 | }
713 |
714 | // See if sorting is needed, update `length` and splice in new models.
715 | if (toAdd.length || (order && order.length)) {
716 | if (sortable) sort = true;
717 | this.length += toAdd.length;
718 | if (at != null) {
719 | splice.apply(this.models, [at, 0].concat(toAdd));
720 | } else {
721 | if (order) this.models.length = 0;
722 | push.apply(this.models, order || toAdd);
723 | }
724 | }
725 |
726 | // Silently sort the collection if appropriate.
727 | if (sort) this.sort({silent: true});
728 |
729 | if (options.silent) return this;
730 |
731 | // Trigger `add` events.
732 | for (i = 0, l = toAdd.length; i < l; i++) {
733 | (model = toAdd[i]).trigger('add', model, this, options);
734 | }
735 |
736 | // Trigger `sort` if the collection was sorted.
737 | if (sort || (order && order.length)) this.trigger('sort', this, options);
738 | return this;
739 | },
740 |
741 | // When you have more items than you want to add or remove individually,
742 | // you can reset the entire set with a new list of models, without firing
743 | // any granular `add` or `remove` events. Fires `reset` when finished.
744 | // Useful for bulk operations and optimizations.
745 | reset: function(models, options) {
746 | options || (options = {});
747 | for (var i = 0, l = this.models.length; i < l; i++) {
748 | this._removeReference(this.models[i]);
749 | }
750 | options.previousModels = this.models;
751 | this._reset();
752 | this.add(models, _.extend({silent: true}, options));
753 | if (!options.silent) this.trigger('reset', this, options);
754 | return this;
755 | },
756 |
757 | // Add a model to the end of the collection.
758 | push: function(model, options) {
759 | model = this._prepareModel(model, options);
760 | this.add(model, _.extend({at: this.length}, options));
761 | return model;
762 | },
763 |
764 | // Remove a model from the end of the collection.
765 | pop: function(options) {
766 | var model = this.at(this.length - 1);
767 | this.remove(model, options);
768 | return model;
769 | },
770 |
771 | // Add a model to the beginning of the collection.
772 | unshift: function(model, options) {
773 | model = this._prepareModel(model, options);
774 | this.add(model, _.extend({at: 0}, options));
775 | return model;
776 | },
777 |
778 | // Remove a model from the beginning of the collection.
779 | shift: function(options) {
780 | var model = this.at(0);
781 | this.remove(model, options);
782 | return model;
783 | },
784 |
785 | // Slice out a sub-array of models from the collection.
786 | slice: function() {
787 | return slice.apply(this.models, arguments);
788 | },
789 |
790 | // Get a model from the set by id.
791 | get: function(obj) {
792 | if (obj == null) return void 0;
793 | return this._byId[obj.id != null ? obj.id : obj.cid || obj];
794 | },
795 |
796 | // Get the model at the given index.
797 | at: function(index) {
798 | return this.models[index];
799 | },
800 |
801 | // Return models with matching attributes. Useful for simple cases of
802 | // `filter`.
803 | where: function(attrs, first) {
804 | if (_.isEmpty(attrs)) return first ? void 0 : [];
805 | return this[first ? 'find' : 'filter'](function(model) {
806 | for (var key in attrs) {
807 | if (attrs[key] !== model.get(key)) return false;
808 | }
809 | return true;
810 | });
811 | },
812 |
813 | // Return the first model with matching attributes. Useful for simple cases
814 | // of `find`.
815 | findWhere: function(attrs) {
816 | return this.where(attrs, true);
817 | },
818 |
819 | // Force the collection to re-sort itself. You don't need to call this under
820 | // normal circumstances, as the set will maintain sort order as each item
821 | // is added.
822 | sort: function(options) {
823 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
824 | options || (options = {});
825 |
826 | // Run sort based on type of `comparator`.
827 | if (_.isString(this.comparator) || this.comparator.length === 1) {
828 | this.models = this.sortBy(this.comparator, this);
829 | } else {
830 | this.models.sort(_.bind(this.comparator, this));
831 | }
832 |
833 | if (!options.silent) this.trigger('sort', this, options);
834 | return this;
835 | },
836 |
837 | // Figure out the smallest index at which a model should be inserted so as
838 | // to maintain order.
839 | sortedIndex: function(model, value, context) {
840 | value || (value = this.comparator);
841 | var iterator = _.isFunction(value) ? value : function(model) {
842 | return model.get(value);
843 | };
844 | return _.sortedIndex(this.models, model, iterator, context);
845 | },
846 |
847 | // Pluck an attribute from each model in the collection.
848 | pluck: function(attr) {
849 | return _.invoke(this.models, 'get', attr);
850 | },
851 |
852 | // Fetch the default set of models for this collection, resetting the
853 | // collection when they arrive. If `reset: true` is passed, the response
854 | // data will be passed through the `reset` method instead of `set`.
855 | fetch: function(options) {
856 | options = options ? _.clone(options) : {};
857 | if (options.parse === void 0) options.parse = true;
858 | var success = options.success;
859 | var collection = this;
860 | options.success = function(resp) {
861 | var method = options.reset ? 'reset' : 'set';
862 | collection[method](resp, options);
863 | if (success) success(collection, resp, options);
864 | collection.trigger('sync', collection, resp, options);
865 | };
866 | wrapError(this, options);
867 | return this.sync('read', this, options);
868 | },
869 |
870 | // Create a new instance of a model in this collection. Add the model to the
871 | // collection immediately, unless `wait: true` is passed, in which case we
872 | // wait for the server to agree.
873 | create: function(model, options) {
874 | options = options ? _.clone(options) : {};
875 | if (!(model = this._prepareModel(model, options))) return false;
876 | if (!options.wait) this.add(model, options);
877 | var collection = this;
878 | var success = options.success;
879 | options.success = function(resp) {
880 | if (options.wait) collection.add(model, options);
881 | if (success) success(model, resp, options);
882 | };
883 | model.save(null, options);
884 | return model;
885 | },
886 |
887 | // **parse** converts a response into a list of models to be added to the
888 | // collection. The default implementation is just to pass it through.
889 | parse: function(resp, options) {
890 | return resp;
891 | },
892 |
893 | // Create a new collection with an identical list of models as this one.
894 | clone: function() {
895 | return new this.constructor(this.models);
896 | },
897 |
898 | // Private method to reset all internal state. Called when the collection
899 | // is first initialized or reset.
900 | _reset: function() {
901 | this.length = 0;
902 | this.models = [];
903 | this._byId = {};
904 | },
905 |
906 | // Prepare a hash of attributes (or other model) to be added to this
907 | // collection.
908 | _prepareModel: function(attrs, options) {
909 | if (attrs instanceof Model) {
910 | if (!attrs.collection) attrs.collection = this;
911 | return attrs;
912 | }
913 | options || (options = {});
914 | options.collection = this;
915 | var model = new this.model(attrs, options);
916 | if (!model._validate(attrs, options)) {
917 | this.trigger('invalid', this, attrs, options);
918 | return false;
919 | }
920 | return model;
921 | },
922 |
923 | // Internal method to sever a model's ties to a collection.
924 | _removeReference: function(model) {
925 | if (this === model.collection) delete model.collection;
926 | model.off('all', this._onModelEvent, this);
927 | },
928 |
929 | // Internal method called every time a model in the set fires an event.
930 | // Sets need to update their indexes when models change ids. All other
931 | // events simply proxy through. "add" and "remove" events that originate
932 | // in other collections are ignored.
933 | _onModelEvent: function(event, model, collection, options) {
934 | if ((event === 'add' || event === 'remove') && collection !== this) return;
935 | if (event === 'destroy') this.remove(model, options);
936 | if (model && event === 'change:' + model.idAttribute) {
937 | delete this._byId[model.previous(model.idAttribute)];
938 | if (model.id != null) this._byId[model.id] = model;
939 | }
940 | this.trigger.apply(this, arguments);
941 | }
942 |
943 | });
944 |
945 | // Underscore methods that we want to implement on the Collection.
946 | // 90% of the core usefulness of Backbone Collections is actually implemented
947 | // right here:
948 | var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
949 | 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
950 | 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
951 | 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
952 | 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
953 | 'isEmpty', 'chain'];
954 |
955 | // Mix in each Underscore method as a proxy to `Collection#models`.
956 | _.each(methods, function(method) {
957 | Collection.prototype[method] = function() {
958 | var args = slice.call(arguments);
959 | args.unshift(this.models);
960 | return _[method].apply(_, args);
961 | };
962 | });
963 |
964 | // Underscore methods that take a property name as an argument.
965 | var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
966 |
967 | // Use attributes instead of properties.
968 | _.each(attributeMethods, function(method) {
969 | Collection.prototype[method] = function(value, context) {
970 | var iterator = _.isFunction(value) ? value : function(model) {
971 | return model.get(value);
972 | };
973 | return _[method](this.models, iterator, context);
974 | };
975 | });
976 |
977 | // Backbone.View
978 | // -------------
979 |
980 | // Backbone Views are almost more convention than they are actual code. A View
981 | // is simply a JavaScript object that represents a logical chunk of UI in the
982 | // DOM. This might be a single item, an entire list, a sidebar or panel, or
983 | // even the surrounding frame which wraps your whole app. Defining a chunk of
984 | // UI as a **View** allows you to define your DOM events declaratively, without
985 | // having to worry about render order ... and makes it easy for the view to
986 | // react to specific changes in the state of your models.
987 |
988 | // Options with special meaning *(e.g. model, collection, id, className)* are
989 | // attached directly to the view. See `viewOptions` for an exhaustive
990 | // list.
991 |
992 | // Creating a Backbone.View creates its initial element outside of the DOM,
993 | // if an existing element is not provided...
994 | var View = Backbone.View = function(options) {
995 | this.cid = _.uniqueId('view');
996 | options || (options = {});
997 | _.extend(this, _.pick(options, viewOptions));
998 | this._ensureElement();
999 | this.initialize.apply(this, arguments);
1000 | this.delegateEvents();
1001 | };
1002 |
1003 | // Cached regex to split keys for `delegate`.
1004 | var delegateEventSplitter = /^(\S+)\s*(.*)$/;
1005 |
1006 | // List of view options to be merged as properties.
1007 | var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1008 |
1009 | // Set up all inheritable **Backbone.View** properties and methods.
1010 | _.extend(View.prototype, Events, {
1011 |
1012 | // The default `tagName` of a View's element is `"div"`.
1013 | tagName: 'div',
1014 |
1015 | // jQuery delegate for element lookup, scoped to DOM elements within the
1016 | // current view. This should be prefered to global lookups where possible.
1017 | $: function(selector) {
1018 | return this.$el.find(selector);
1019 | },
1020 |
1021 | // Initialize is an empty function by default. Override it with your own
1022 | // initialization logic.
1023 | initialize: function(){},
1024 |
1025 | // **render** is the core function that your view should override, in order
1026 | // to populate its element (`this.el`), with the appropriate HTML. The
1027 | // convention is for **render** to always return `this`.
1028 | render: function() {
1029 | return this;
1030 | },
1031 |
1032 | // Remove this view by taking the element out of the DOM, and removing any
1033 | // applicable Backbone.Events listeners.
1034 | remove: function() {
1035 | this.$el.remove();
1036 | this.stopListening();
1037 | return this;
1038 | },
1039 |
1040 | // Change the view's element (`this.el` property), including event
1041 | // re-delegation.
1042 | setElement: function(element, delegate) {
1043 | if (this.$el) this.undelegateEvents();
1044 | this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
1045 | this.el = this.$el[0];
1046 | if (delegate !== false) this.delegateEvents();
1047 | return this;
1048 | },
1049 |
1050 | // Set callbacks, where `this.events` is a hash of
1051 | //
1052 | // *{"event selector": "callback"}*
1053 | //
1054 | // {
1055 | // 'mousedown .title': 'edit',
1056 | // 'click .button': 'save'
1057 | // 'click .open': function(e) { ... }
1058 | // }
1059 | //
1060 | // pairs. Callbacks will be bound to the view, with `this` set properly.
1061 | // Uses event delegation for efficiency.
1062 | // Omitting the selector binds the event to `this.el`.
1063 | // This only works for delegate-able events: not `focus`, `blur`, and
1064 | // not `change`, `submit`, and `reset` in Internet Explorer.
1065 | delegateEvents: function(events) {
1066 | if (!(events || (events = _.result(this, 'events')))) return this;
1067 | this.undelegateEvents();
1068 | for (var key in events) {
1069 | var method = events[key];
1070 | if (!_.isFunction(method)) method = this[events[key]];
1071 | if (!method) continue;
1072 |
1073 | var match = key.match(delegateEventSplitter);
1074 | var eventName = match[1], selector = match[2];
1075 | method = _.bind(method, this);
1076 | eventName += '.delegateEvents' + this.cid;
1077 | if (selector === '') {
1078 | this.$el.on(eventName, method);
1079 | } else {
1080 | this.$el.on(eventName, selector, method);
1081 | }
1082 | }
1083 | return this;
1084 | },
1085 |
1086 | // Clears all callbacks previously bound to the view with `delegateEvents`.
1087 | // You usually don't need to use this, but may wish to if you have multiple
1088 | // Backbone views attached to the same DOM element.
1089 | undelegateEvents: function() {
1090 | this.$el.off('.delegateEvents' + this.cid);
1091 | return this;
1092 | },
1093 |
1094 | // Ensure that the View has a DOM element to render into.
1095 | // If `this.el` is a string, pass it through `$()`, take the first
1096 | // matching element, and re-assign it to `el`. Otherwise, create
1097 | // an element from the `id`, `className` and `tagName` properties.
1098 | _ensureElement: function() {
1099 | if (!this.el) {
1100 | var attrs = _.extend({}, _.result(this, 'attributes'));
1101 | if (this.id) attrs.id = _.result(this, 'id');
1102 | if (this.className) attrs['class'] = _.result(this, 'className');
1103 | var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
1104 | this.setElement($el, false);
1105 | } else {
1106 | this.setElement(_.result(this, 'el'), false);
1107 | }
1108 | }
1109 |
1110 | });
1111 |
1112 | // Backbone.sync
1113 | // -------------
1114 |
1115 | // Override this function to change the manner in which Backbone persists
1116 | // models to the server. You will be passed the type of request, and the
1117 | // model in question. By default, makes a RESTful Ajax request
1118 | // to the model's `url()`. Some possible customizations could be:
1119 | //
1120 | // * Use `setTimeout` to batch rapid-fire updates into a single request.
1121 | // * Send up the models as XML instead of JSON.
1122 | // * Persist models via WebSockets instead of Ajax.
1123 | //
1124 | // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1125 | // as `POST`, with a `_method` parameter containing the true HTTP method,
1126 | // as well as all requests with the body as `application/x-www-form-urlencoded`
1127 | // instead of `application/json` with the model in a param named `model`.
1128 | // Useful when interfacing with server-side languages like **PHP** that make
1129 | // it difficult to read the body of `PUT` requests.
1130 | Backbone.sync = function(method, model, options) {
1131 | var type = methodMap[method];
1132 |
1133 | // Default options, unless specified.
1134 | _.defaults(options || (options = {}), {
1135 | emulateHTTP: Backbone.emulateHTTP,
1136 | emulateJSON: Backbone.emulateJSON
1137 | });
1138 |
1139 | // Default JSON-request options.
1140 | var params = {type: type, dataType: 'json'};
1141 |
1142 | // Ensure that we have a URL.
1143 | if (!options.url) {
1144 | params.url = _.result(model, 'url') || urlError();
1145 | }
1146 |
1147 | // Ensure that we have the appropriate request data.
1148 | if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1149 | params.contentType = 'application/json';
1150 | params.data = JSON.stringify(options.attrs || model.toJSON(options));
1151 | }
1152 |
1153 | // For older servers, emulate JSON by encoding the request into an HTML-form.
1154 | if (options.emulateJSON) {
1155 | params.contentType = 'application/x-www-form-urlencoded';
1156 | params.data = params.data ? {model: params.data} : {};
1157 | }
1158 |
1159 | // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1160 | // And an `X-HTTP-Method-Override` header.
1161 | if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1162 | params.type = 'POST';
1163 | if (options.emulateJSON) params.data._method = type;
1164 | var beforeSend = options.beforeSend;
1165 | options.beforeSend = function(xhr) {
1166 | xhr.setRequestHeader('X-HTTP-Method-Override', type);
1167 | if (beforeSend) return beforeSend.apply(this, arguments);
1168 | };
1169 | }
1170 |
1171 | // Don't process data on a non-GET request.
1172 | if (params.type !== 'GET' && !options.emulateJSON) {
1173 | params.processData = false;
1174 | }
1175 |
1176 | // If we're sending a `PATCH` request, and we're in an old Internet Explorer
1177 | // that still has ActiveX enabled by default, override jQuery to use that
1178 | // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
1179 | if (params.type === 'PATCH' && window.ActiveXObject &&
1180 | !(window.external && window.external.msActiveXFilteringEnabled)) {
1181 | params.xhr = function() {
1182 | return new ActiveXObject("Microsoft.XMLHTTP");
1183 | };
1184 | }
1185 |
1186 | // Make the request, allowing the user to override any Ajax options.
1187 | var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1188 | model.trigger('request', model, xhr, options);
1189 | return xhr;
1190 | };
1191 |
1192 | // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1193 | var methodMap = {
1194 | 'create': 'POST',
1195 | 'update': 'PUT',
1196 | 'patch': 'PATCH',
1197 | 'delete': 'DELETE',
1198 | 'read': 'GET'
1199 | };
1200 |
1201 | // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1202 | // Override this if you'd like to use a different library.
1203 | Backbone.ajax = function() {
1204 | return Backbone.$.ajax.apply(Backbone.$, arguments);
1205 | };
1206 |
1207 | // Backbone.Router
1208 | // ---------------
1209 |
1210 | // Routers map faux-URLs to actions, and fire events when routes are
1211 | // matched. Creating a new one sets its `routes` hash, if not set statically.
1212 | var Router = Backbone.Router = function(options) {
1213 | options || (options = {});
1214 | if (options.routes) this.routes = options.routes;
1215 | this._bindRoutes();
1216 | this.initialize.apply(this, arguments);
1217 | };
1218 |
1219 | // Cached regular expressions for matching named param parts and splatted
1220 | // parts of route strings.
1221 | var optionalParam = /\((.*?)\)/g;
1222 | var namedParam = /(\(\?)?:\w+/g;
1223 | var splatParam = /\*\w+/g;
1224 | var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1225 |
1226 | // Set up all inheritable **Backbone.Router** properties and methods.
1227 | _.extend(Router.prototype, Events, {
1228 |
1229 | // Initialize is an empty function by default. Override it with your own
1230 | // initialization logic.
1231 | initialize: function(){},
1232 |
1233 | // Manually bind a single named route to a callback. For example:
1234 | //
1235 | // this.route('search/:query/p:num', 'search', function(query, num) {
1236 | // ...
1237 | // });
1238 | //
1239 | route: function(route, name, callback) {
1240 | if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1241 | if (_.isFunction(name)) {
1242 | callback = name;
1243 | name = '';
1244 | }
1245 | if (!callback) callback = this[name];
1246 | var router = this;
1247 | Backbone.history.route(route, function(fragment) {
1248 | var args = router._extractParameters(route, fragment);
1249 | callback && callback.apply(router, args);
1250 | router.trigger.apply(router, ['route:' + name].concat(args));
1251 | router.trigger('route', name, args);
1252 | Backbone.history.trigger('route', router, name, args);
1253 | });
1254 | return this;
1255 | },
1256 |
1257 | // Simple proxy to `Backbone.history` to save a fragment into the history.
1258 | navigate: function(fragment, options) {
1259 | Backbone.history.navigate(fragment, options);
1260 | return this;
1261 | },
1262 |
1263 | // Bind all defined routes to `Backbone.history`. We have to reverse the
1264 | // order of the routes here to support behavior where the most general
1265 | // routes can be defined at the bottom of the route map.
1266 | _bindRoutes: function() {
1267 | if (!this.routes) return;
1268 | this.routes = _.result(this, 'routes');
1269 | var route, routes = _.keys(this.routes);
1270 | while ((route = routes.pop()) != null) {
1271 | this.route(route, this.routes[route]);
1272 | }
1273 | },
1274 |
1275 | // Convert a route string into a regular expression, suitable for matching
1276 | // against the current location hash.
1277 | _routeToRegExp: function(route) {
1278 | route = route.replace(escapeRegExp, '\\$&')
1279 | .replace(optionalParam, '(?:$1)?')
1280 | .replace(namedParam, function(match, optional){
1281 | return optional ? match : '([^\/]+)';
1282 | })
1283 | .replace(splatParam, '(.*?)');
1284 | return new RegExp('^' + route + '$');
1285 | },
1286 |
1287 | // Given a route, and a URL fragment that it matches, return the array of
1288 | // extracted decoded parameters. Empty or unmatched parameters will be
1289 | // treated as `null` to normalize cross-browser behavior.
1290 | _extractParameters: function(route, fragment) {
1291 | var params = route.exec(fragment).slice(1);
1292 | return _.map(params, function(param) {
1293 | return param ? decodeURIComponent(param) : null;
1294 | });
1295 | }
1296 |
1297 | });
1298 |
1299 | // Backbone.History
1300 | // ----------------
1301 |
1302 | // Handles cross-browser history management, based on either
1303 | // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
1304 | // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
1305 | // and URL fragments. If the browser supports neither (old IE, natch),
1306 | // falls back to polling.
1307 | var History = Backbone.History = function() {
1308 | this.handlers = [];
1309 | _.bindAll(this, 'checkUrl');
1310 |
1311 | // Ensure that `History` can be used outside of the browser.
1312 | if (typeof window !== 'undefined') {
1313 | this.location = window.location;
1314 | this.history = window.history;
1315 | }
1316 | };
1317 |
1318 | // Cached regex for stripping a leading hash/slash and trailing space.
1319 | var routeStripper = /^[#\/]|\s+$/g;
1320 |
1321 | // Cached regex for stripping leading and trailing slashes.
1322 | var rootStripper = /^\/+|\/+$/g;
1323 |
1324 | // Cached regex for detecting MSIE.
1325 | var isExplorer = /msie [\w.]+/;
1326 |
1327 | // Cached regex for removing a trailing slash.
1328 | var trailingSlash = /\/$/;
1329 |
1330 | // Has the history handling already been started?
1331 | History.started = false;
1332 |
1333 | // Set up all inheritable **Backbone.History** properties and methods.
1334 | _.extend(History.prototype, Events, {
1335 |
1336 | // The default interval to poll for hash changes, if necessary, is
1337 | // twenty times a second.
1338 | interval: 50,
1339 |
1340 | // Gets the true hash value. Cannot use location.hash directly due to bug
1341 | // in Firefox where location.hash will always be decoded.
1342 | getHash: function(window) {
1343 | var match = (window || this).location.href.match(/#(.*)$/);
1344 | return match ? match[1] : '';
1345 | },
1346 |
1347 | // Get the cross-browser normalized URL fragment, either from the URL,
1348 | // the hash, or the override.
1349 | getFragment: function(fragment, forcePushState) {
1350 | if (fragment == null) {
1351 | if (this._hasPushState || !this._wantsHashChange || forcePushState) {
1352 | fragment = this.location.pathname;
1353 | var root = this.root.replace(trailingSlash, '');
1354 | if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
1355 | } else {
1356 | fragment = this.getHash();
1357 | }
1358 | }
1359 | return fragment.replace(routeStripper, '');
1360 | },
1361 |
1362 | // Start the hash change handling, returning `true` if the current URL matches
1363 | // an existing route, and `false` otherwise.
1364 | start: function(options) {
1365 | if (History.started) throw new Error("Backbone.history has already been started");
1366 | History.started = true;
1367 |
1368 | // Figure out the initial configuration. Do we need an iframe?
1369 | // Is pushState desired ... is it available?
1370 | this.options = _.extend({}, {root: '/'}, this.options, options);
1371 | this.root = this.options.root;
1372 | this._wantsHashChange = this.options.hashChange !== false;
1373 | this._wantsPushState = !!this.options.pushState;
1374 | this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
1375 | var fragment = this.getFragment();
1376 | var docMode = document.documentMode;
1377 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
1378 |
1379 | // Normalize root to always include a leading and trailing slash.
1380 | this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1381 |
1382 | if (oldIE && this._wantsHashChange) {
1383 | this.iframe = Backbone.$('').hide().appendTo('body')[0].contentWindow;
1384 | this.navigate(fragment);
1385 | }
1386 |
1387 | // Depending on whether we're using pushState or hashes, and whether
1388 | // 'onhashchange' is supported, determine how we check the URL state.
1389 | if (this._hasPushState) {
1390 | Backbone.$(window).on('popstate', this.checkUrl);
1391 | } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
1392 | Backbone.$(window).on('hashchange', this.checkUrl);
1393 | } else if (this._wantsHashChange) {
1394 | this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1395 | }
1396 |
1397 | // Determine if we need to change the base url, for a pushState link
1398 | // opened by a non-pushState browser.
1399 | this.fragment = fragment;
1400 | var loc = this.location;
1401 | var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
1402 |
1403 | // If we've started off with a route from a `pushState`-enabled browser,
1404 | // but we're currently in a browser that doesn't support it...
1405 | if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
1406 | this.fragment = this.getFragment(null, true);
1407 | this.location.replace(this.root + this.location.search + '#' + this.fragment);
1408 | // Return immediately as browser will do redirect to new url
1409 | return true;
1410 |
1411 | // Or if we've started out with a hash-based route, but we're currently
1412 | // in a browser where it could be `pushState`-based instead...
1413 | } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
1414 | this.fragment = this.getHash().replace(routeStripper, '');
1415 | this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
1416 | }
1417 |
1418 | if (!this.options.silent) return this.loadUrl();
1419 | },
1420 |
1421 | // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1422 | // but possibly useful for unit testing Routers.
1423 | stop: function() {
1424 | Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
1425 | clearInterval(this._checkUrlInterval);
1426 | History.started = false;
1427 | },
1428 |
1429 | // Add a route to be tested when the fragment changes. Routes added later
1430 | // may override previous routes.
1431 | route: function(route, callback) {
1432 | this.handlers.unshift({route: route, callback: callback});
1433 | },
1434 |
1435 | // Checks the current URL to see if it has changed, and if it has,
1436 | // calls `loadUrl`, normalizing across the hidden iframe.
1437 | checkUrl: function(e) {
1438 | var current = this.getFragment();
1439 | if (current === this.fragment && this.iframe) {
1440 | current = this.getFragment(this.getHash(this.iframe));
1441 | }
1442 | if (current === this.fragment) return false;
1443 | if (this.iframe) this.navigate(current);
1444 | this.loadUrl() || this.loadUrl(this.getHash());
1445 | },
1446 |
1447 | // Attempt to load the current URL fragment. If a route succeeds with a
1448 | // match, returns `true`. If no defined routes matches the fragment,
1449 | // returns `false`.
1450 | loadUrl: function(fragmentOverride) {
1451 | var fragment = this.fragment = this.getFragment(fragmentOverride);
1452 | var matched = _.any(this.handlers, function(handler) {
1453 | if (handler.route.test(fragment)) {
1454 | handler.callback(fragment);
1455 | return true;
1456 | }
1457 | });
1458 | return matched;
1459 | },
1460 |
1461 | // Save a fragment into the hash history, or replace the URL state if the
1462 | // 'replace' option is passed. You are responsible for properly URL-encoding
1463 | // the fragment in advance.
1464 | //
1465 | // The options object can contain `trigger: true` if you wish to have the
1466 | // route callback be fired (not usually desirable), or `replace: true`, if
1467 | // you wish to modify the current URL without adding an entry to the history.
1468 | navigate: function(fragment, options) {
1469 | if (!History.started) return false;
1470 | if (!options || options === true) options = {trigger: options};
1471 | fragment = this.getFragment(fragment || '');
1472 | if (this.fragment === fragment) return;
1473 | this.fragment = fragment;
1474 | var url = this.root + fragment;
1475 |
1476 | // If pushState is available, we use it to set the fragment as a real URL.
1477 | if (this._hasPushState) {
1478 | this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1479 |
1480 | // If hash changes haven't been explicitly disabled, update the hash
1481 | // fragment to store history.
1482 | } else if (this._wantsHashChange) {
1483 | this._updateHash(this.location, fragment, options.replace);
1484 | if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
1485 | // Opening and closing the iframe tricks IE7 and earlier to push a
1486 | // history entry on hash-tag change. When replace is true, we don't
1487 | // want this.
1488 | if(!options.replace) this.iframe.document.open().close();
1489 | this._updateHash(this.iframe.location, fragment, options.replace);
1490 | }
1491 |
1492 | // If you've told us that you explicitly don't want fallback hashchange-
1493 | // based history, then `navigate` becomes a page refresh.
1494 | } else {
1495 | return this.location.assign(url);
1496 | }
1497 | if (options.trigger) return this.loadUrl(fragment);
1498 | },
1499 |
1500 | // Update the hash location, either replacing the current entry, or adding
1501 | // a new one to the browser history.
1502 | _updateHash: function(location, fragment, replace) {
1503 | if (replace) {
1504 | var href = location.href.replace(/(javascript:|#).*$/, '');
1505 | location.replace(href + '#' + fragment);
1506 | } else {
1507 | // Some browsers require that `hash` contains a leading #.
1508 | location.hash = '#' + fragment;
1509 | }
1510 | }
1511 |
1512 | });
1513 |
1514 | // Create the default Backbone.history.
1515 | Backbone.history = new History;
1516 |
1517 | // Helpers
1518 | // -------
1519 |
1520 | // Helper function to correctly set up the prototype chain, for subclasses.
1521 | // Similar to `goog.inherits`, but uses a hash of prototype properties and
1522 | // class properties to be extended.
1523 | var extend = function(protoProps, staticProps) {
1524 | var parent = this;
1525 | var child;
1526 |
1527 | // The constructor function for the new subclass is either defined by you
1528 | // (the "constructor" property in your `extend` definition), or defaulted
1529 | // by us to simply call the parent's constructor.
1530 | if (protoProps && _.has(protoProps, 'constructor')) {
1531 | child = protoProps.constructor;
1532 | } else {
1533 | child = function(){ return parent.apply(this, arguments); };
1534 | }
1535 |
1536 | // Add static properties to the constructor function, if supplied.
1537 | _.extend(child, parent, staticProps);
1538 |
1539 | // Set the prototype chain to inherit from `parent`, without calling
1540 | // `parent`'s constructor function.
1541 | var Surrogate = function(){ this.constructor = child; };
1542 | Surrogate.prototype = parent.prototype;
1543 | child.prototype = new Surrogate;
1544 |
1545 | // Add prototype properties (instance properties) to the subclass,
1546 | // if supplied.
1547 | if (protoProps) _.extend(child.prototype, protoProps);
1548 |
1549 | // Set a convenience property in case the parent's prototype is needed
1550 | // later.
1551 | child.__super__ = parent.prototype;
1552 |
1553 | return child;
1554 | };
1555 |
1556 | // Set up inheritance for the model, collection, router, view and history.
1557 | Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
1558 |
1559 | // Throw an error when a URL is needed, and none is supplied.
1560 | var urlError = function() {
1561 | throw new Error('A "url" property or function must be specified');
1562 | };
1563 |
1564 | // Wrap an optional error callback with a fallback error event.
1565 | var wrapError = function(model, options) {
1566 | var error = options.error;
1567 | options.error = function(resp) {
1568 | if (error) error(model, resp, options);
1569 | model.trigger('error', model, resp, options);
1570 | };
1571 | };
1572 |
1573 | }).call(this);
1574 |
--------------------------------------------------------------------------------
/tests/vendor/qunit.css:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.3.0pre - A JavaScript Unit Testing Framework
3 | *
4 | * http://docs.jquery.com/QUnit
5 | *
6 | * Copyright (c) 2011 John Resig, Jörn Zaefferer
7 | * Dual licensed under the MIT (MIT-LICENSE.txt)
8 | * or GPL (GPL-LICENSE.txt) licenses.
9 | */
10 |
11 | /** Font Family and Sizes */
12 |
13 | #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
14 | font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
15 | }
16 |
17 | #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
18 | #qunit-tests { font-size: smaller; }
19 |
20 |
21 | /** Resets */
22 |
23 | #qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
24 | margin: 0;
25 | padding: 0;
26 | }
27 |
28 |
29 | /** Header */
30 |
31 | #qunit-header {
32 | padding: 0.5em 0 0.5em 1em;
33 |
34 | color: #8699a4;
35 | background-color: #0d3349;
36 |
37 | font-size: 1.5em;
38 | line-height: 1em;
39 | font-weight: normal;
40 |
41 | border-radius: 15px 15px 0 0;
42 | -moz-border-radius: 15px 15px 0 0;
43 | -webkit-border-top-right-radius: 15px;
44 | -webkit-border-top-left-radius: 15px;
45 | }
46 |
47 | #qunit-header a {
48 | text-decoration: none;
49 | color: #c2ccd1;
50 | }
51 |
52 | #qunit-header a:hover,
53 | #qunit-header a:focus {
54 | color: #fff;
55 | }
56 |
57 | #qunit-banner {
58 | height: 5px;
59 | }
60 |
61 | #qunit-testrunner-toolbar {
62 | padding: 0.5em 0 0.5em 2em;
63 | color: #5E740B;
64 | background-color: #eee;
65 | }
66 |
67 | #qunit-userAgent {
68 | padding: 0.5em 0 0.5em 2.5em;
69 | background-color: #2b81af;
70 | color: #fff;
71 | text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
72 | }
73 |
74 |
75 | /** Tests: Pass/Fail */
76 |
77 | #qunit-tests {
78 | list-style-position: inside;
79 | }
80 |
81 | #qunit-tests li {
82 | padding: 0.4em 0.5em 0.4em 2.5em;
83 | border-bottom: 1px solid #fff;
84 | list-style-position: inside;
85 | }
86 |
87 | #qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running {
88 | display: none;
89 | }
90 |
91 | #qunit-tests li strong {
92 | cursor: pointer;
93 | }
94 |
95 | #qunit-tests li a {
96 | padding: 0.5em;
97 | color: #c2ccd1;
98 | text-decoration: none;
99 | }
100 | #qunit-tests li a:hover,
101 | #qunit-tests li a:focus {
102 | color: #000;
103 | }
104 |
105 | #qunit-tests ol {
106 | margin-top: 0.5em;
107 | padding: 0.5em;
108 |
109 | background-color: #fff;
110 |
111 | border-radius: 15px;
112 | -moz-border-radius: 15px;
113 | -webkit-border-radius: 15px;
114 |
115 | box-shadow: inset 0px 2px 13px #999;
116 | -moz-box-shadow: inset 0px 2px 13px #999;
117 | -webkit-box-shadow: inset 0px 2px 13px #999;
118 | }
119 |
120 | #qunit-tests table {
121 | border-collapse: collapse;
122 | margin-top: .2em;
123 | }
124 |
125 | #qunit-tests th {
126 | text-align: right;
127 | vertical-align: top;
128 | padding: 0 .5em 0 0;
129 | }
130 |
131 | #qunit-tests td {
132 | vertical-align: top;
133 | }
134 |
135 | #qunit-tests pre {
136 | margin: 0;
137 | white-space: pre-wrap;
138 | word-wrap: break-word;
139 | }
140 |
141 | #qunit-tests del {
142 | background-color: #e0f2be;
143 | color: #374e0c;
144 | text-decoration: none;
145 | }
146 |
147 | #qunit-tests ins {
148 | background-color: #ffcaca;
149 | color: #500;
150 | text-decoration: none;
151 | }
152 |
153 | /*** Test Counts */
154 |
155 | #qunit-tests b.counts { color: black; }
156 | #qunit-tests b.passed { color: #5E740B; }
157 | #qunit-tests b.failed { color: #710909; }
158 |
159 | #qunit-tests li li {
160 | margin: 0.5em;
161 | padding: 0.4em 0.5em 0.4em 0.5em;
162 | background-color: #fff;
163 | border-bottom: none;
164 | list-style-position: inside;
165 | }
166 |
167 | /*** Passing Styles */
168 |
169 | #qunit-tests li li.pass {
170 | color: #5E740B;
171 | background-color: #fff;
172 | border-left: 26px solid #C6E746;
173 | }
174 |
175 | #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
176 | #qunit-tests .pass .test-name { color: #366097; }
177 |
178 | #qunit-tests .pass .test-actual,
179 | #qunit-tests .pass .test-expected { color: #999999; }
180 |
181 | #qunit-banner.qunit-pass { background-color: #C6E746; }
182 |
183 | /*** Failing Styles */
184 |
185 | #qunit-tests li li.fail {
186 | color: #710909;
187 | background-color: #fff;
188 | border-left: 26px solid #EE5757;
189 | white-space: pre;
190 | }
191 |
192 | #qunit-tests > li:last-child {
193 | border-radius: 0 0 15px 15px;
194 | -moz-border-radius: 0 0 15px 15px;
195 | -webkit-border-bottom-right-radius: 15px;
196 | -webkit-border-bottom-left-radius: 15px;
197 | }
198 |
199 | #qunit-tests .fail { color: #000000; background-color: #EE5757; }
200 | #qunit-tests .fail .test-name,
201 | #qunit-tests .fail .module-name { color: #000000; }
202 |
203 | #qunit-tests .fail .test-actual { color: #EE5757; }
204 | #qunit-tests .fail .test-expected { color: green; }
205 |
206 | #qunit-banner.qunit-fail { background-color: #EE5757; }
207 |
208 |
209 | /** Result */
210 |
211 | #qunit-testresult {
212 | padding: 0.5em 0.5em 0.5em 2.5em;
213 |
214 | color: #2b81af;
215 | background-color: #D2E0E6;
216 |
217 | border-bottom: 1px solid white;
218 | }
219 |
220 | /** Fixture */
221 |
222 | #qunit-fixture {
223 | position: absolute;
224 | top: -10000px;
225 | left: -10000px;
226 | }
227 |
--------------------------------------------------------------------------------
/tests/vendor/qunit.js:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.3.0pre - A JavaScript Unit Testing Framework
3 | *
4 | * http://docs.jquery.com/QUnit
5 | *
6 | * Copyright (c) 2011 John Resig, Jörn Zaefferer
7 | * Dual licensed under the MIT (MIT-LICENSE.txt)
8 | * or GPL (GPL-LICENSE.txt) licenses.
9 | */
10 |
11 | (function(window) {
12 |
13 | var defined = {
14 | setTimeout: typeof window.setTimeout !== "undefined",
15 | sessionStorage: (function() {
16 | try {
17 | return !!sessionStorage.getItem;
18 | } catch(e) {
19 | return false;
20 | }
21 | })()
22 | };
23 |
24 | var testId = 0,
25 | toString = Object.prototype.toString,
26 | hasOwn = Object.prototype.hasOwnProperty;
27 |
28 | var Test = function(name, testName, expected, testEnvironmentArg, async, callback) {
29 | this.name = name;
30 | this.testName = testName;
31 | this.expected = expected;
32 | this.testEnvironmentArg = testEnvironmentArg;
33 | this.async = async;
34 | this.callback = callback;
35 | this.assertions = [];
36 | };
37 | Test.prototype = {
38 | init: function() {
39 | var tests = id("qunit-tests");
40 | if (tests) {
41 | var b = document.createElement("strong");
42 | b.innerHTML = "Running " + this.name;
43 | var li = document.createElement("li");
44 | li.appendChild( b );
45 | li.className = "running";
46 | li.id = this.id = "test-output" + testId++;
47 | tests.appendChild( li );
48 | }
49 | },
50 | setup: function() {
51 | if (this.module != config.previousModule) {
52 | if ( config.previousModule ) {
53 | runLoggingCallbacks('moduleDone', QUnit, {
54 | name: config.previousModule,
55 | failed: config.moduleStats.bad,
56 | passed: config.moduleStats.all - config.moduleStats.bad,
57 | total: config.moduleStats.all
58 | } );
59 | }
60 | config.previousModule = this.module;
61 | config.moduleStats = { all: 0, bad: 0 };
62 | runLoggingCallbacks( 'moduleStart', QUnit, {
63 | name: this.module
64 | } );
65 | }
66 |
67 | config.current = this;
68 | this.testEnvironment = extend({
69 | setup: function() {},
70 | teardown: function() {}
71 | }, this.moduleTestEnvironment);
72 | if (this.testEnvironmentArg) {
73 | extend(this.testEnvironment, this.testEnvironmentArg);
74 | }
75 |
76 | runLoggingCallbacks( 'testStart', QUnit, {
77 | name: this.testName,
78 | module: this.module
79 | });
80 |
81 | // allow utility functions to access the current test environment
82 | // TODO why??
83 | QUnit.current_testEnvironment = this.testEnvironment;
84 |
85 | try {
86 | if ( !config.pollution ) {
87 | saveGlobal();
88 | }
89 |
90 | this.testEnvironment.setup.call(this.testEnvironment);
91 | } catch(e) {
92 | QUnit.ok( false, "Setup failed on " + this.testName + ": " + e.message );
93 | }
94 | },
95 | run: function() {
96 | config.current = this;
97 | if ( this.async ) {
98 | QUnit.stop();
99 | }
100 |
101 | if ( config.notrycatch ) {
102 | this.callback.call(this.testEnvironment);
103 | return;
104 | }
105 | try {
106 | this.callback.call(this.testEnvironment);
107 | } catch(e) {
108 | fail("Test " + this.testName + " died, exception and test follows", e, this.callback);
109 | QUnit.ok( false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e) );
110 | // else next test will carry the responsibility
111 | saveGlobal();
112 |
113 | // Restart the tests if they're blocking
114 | if ( config.blocking ) {
115 | QUnit.start();
116 | }
117 | }
118 | },
119 | teardown: function() {
120 | config.current = this;
121 | try {
122 | this.testEnvironment.teardown.call(this.testEnvironment);
123 | checkPollution();
124 | } catch(e) {
125 | QUnit.ok( false, "Teardown failed on " + this.testName + ": " + e.message );
126 | }
127 | },
128 | finish: function() {
129 | config.current = this;
130 | if ( this.expected != null && this.expected != this.assertions.length ) {
131 | QUnit.ok( false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" );
132 | }
133 |
134 | var good = 0, bad = 0,
135 | tests = id("qunit-tests");
136 |
137 | config.stats.all += this.assertions.length;
138 | config.moduleStats.all += this.assertions.length;
139 |
140 | if ( tests ) {
141 | var ol = document.createElement("ol");
142 |
143 | for ( var i = 0; i < this.assertions.length; i++ ) {
144 | var assertion = this.assertions[i];
145 |
146 | var li = document.createElement("li");
147 | li.className = assertion.result ? "pass" : "fail";
148 | li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed");
149 | ol.appendChild( li );
150 |
151 | if ( assertion.result ) {
152 | good++;
153 | } else {
154 | bad++;
155 | config.stats.bad++;
156 | config.moduleStats.bad++;
157 | }
158 | }
159 |
160 | // store result when possible
161 | if ( QUnit.config.reorder && defined.sessionStorage ) {
162 | if (bad) {
163 | sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad);
164 | } else {
165 | sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName);
166 | }
167 | }
168 |
169 | if (bad == 0) {
170 | ol.style.display = "none";
171 | }
172 |
173 | var b = document.createElement("strong");
174 | b.innerHTML = this.name + " (" + bad + " , " + good + " , " + this.assertions.length + ") ";
175 |
176 | var a = document.createElement("a");
177 | a.innerHTML = "Rerun";
178 | a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
179 |
180 | addEvent(b, "click", function() {
181 | var next = b.nextSibling.nextSibling,
182 | display = next.style.display;
183 | next.style.display = display === "none" ? "block" : "none";
184 | });
185 |
186 | addEvent(b, "dblclick", function(e) {
187 | var target = e && e.target ? e.target : window.event.srcElement;
188 | if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
189 | target = target.parentNode;
190 | }
191 | if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
192 | window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") });
193 | }
194 | });
195 |
196 | var li = id(this.id);
197 | li.className = bad ? "fail" : "pass";
198 | li.removeChild( li.firstChild );
199 | li.appendChild( b );
200 | li.appendChild( a );
201 | li.appendChild( ol );
202 |
203 | } else {
204 | for ( var i = 0; i < this.assertions.length; i++ ) {
205 | if ( !this.assertions[i].result ) {
206 | bad++;
207 | config.stats.bad++;
208 | config.moduleStats.bad++;
209 | }
210 | }
211 | }
212 |
213 | try {
214 | QUnit.reset();
215 | } catch(e) {
216 | fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset);
217 | }
218 |
219 | runLoggingCallbacks( 'testDone', QUnit, {
220 | name: this.testName,
221 | module: this.module,
222 | failed: bad,
223 | passed: this.assertions.length - bad,
224 | total: this.assertions.length
225 | } );
226 | },
227 |
228 | queue: function() {
229 | var test = this;
230 | synchronize(function() {
231 | test.init();
232 | });
233 | function run() {
234 | // each of these can by async
235 | synchronize(function() {
236 | test.setup();
237 | });
238 | synchronize(function() {
239 | test.run();
240 | });
241 | synchronize(function() {
242 | test.teardown();
243 | });
244 | synchronize(function() {
245 | test.finish();
246 | });
247 | }
248 | // defer when previous test run passed, if storage is available
249 | var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName);
250 | if (bad) {
251 | run();
252 | } else {
253 | synchronize(run, true);
254 | };
255 | }
256 |
257 | };
258 |
259 | var QUnit = {
260 |
261 | // call on start of module test to prepend name to all tests
262 | module: function(name, testEnvironment) {
263 | config.currentModule = name;
264 | config.currentModuleTestEnviroment = testEnvironment;
265 | },
266 |
267 | asyncTest: function(testName, expected, callback) {
268 | if ( arguments.length === 2 ) {
269 | callback = expected;
270 | expected = null;
271 | }
272 |
273 | QUnit.test(testName, expected, callback, true);
274 | },
275 |
276 | test: function(testName, expected, callback, async) {
277 | var name = '' + escapeInnerText(testName) + ' ', testEnvironmentArg;
278 |
279 | if ( arguments.length === 2 ) {
280 | callback = expected;
281 | expected = null;
282 | }
283 | // is 2nd argument a testEnvironment?
284 | if ( expected && typeof expected === 'object') {
285 | testEnvironmentArg = expected;
286 | expected = null;
287 | }
288 |
289 | if ( config.currentModule ) {
290 | name = '' + config.currentModule + " : " + name;
291 | }
292 |
293 | if ( !validTest(config.currentModule + ": " + testName) ) {
294 | return;
295 | }
296 |
297 | var test = new Test(name, testName, expected, testEnvironmentArg, async, callback);
298 | test.module = config.currentModule;
299 | test.moduleTestEnvironment = config.currentModuleTestEnviroment;
300 | test.queue();
301 | },
302 |
303 | /**
304 | * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
305 | */
306 | expect: function(asserts) {
307 | config.current.expected = asserts;
308 | },
309 |
310 | /**
311 | * Asserts true.
312 | * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
313 | */
314 | ok: function(a, msg) {
315 | a = !!a;
316 | var details = {
317 | result: a,
318 | message: msg
319 | };
320 | msg = escapeInnerText(msg);
321 | runLoggingCallbacks( 'log', QUnit, details );
322 | config.current.assertions.push({
323 | result: a,
324 | message: msg
325 | });
326 | },
327 |
328 | /**
329 | * Checks that the first two arguments are equal, with an optional message.
330 | * Prints out both actual and expected values.
331 | *
332 | * Prefered to ok( actual == expected, message )
333 | *
334 | * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." );
335 | *
336 | * @param Object actual
337 | * @param Object expected
338 | * @param String message (optional)
339 | */
340 | equal: function(actual, expected, message) {
341 | QUnit.push(expected == actual, actual, expected, message);
342 | },
343 |
344 | notEqual: function(actual, expected, message) {
345 | QUnit.push(expected != actual, actual, expected, message);
346 | },
347 |
348 | deepEqual: function(actual, expected, message) {
349 | QUnit.push(QUnit.equiv(actual, expected), actual, expected, message);
350 | },
351 |
352 | notDeepEqual: function(actual, expected, message) {
353 | QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message);
354 | },
355 |
356 | strictEqual: function(actual, expected, message) {
357 | QUnit.push(expected === actual, actual, expected, message);
358 | },
359 |
360 | notStrictEqual: function(actual, expected, message) {
361 | QUnit.push(expected !== actual, actual, expected, message);
362 | },
363 |
364 | raises: function(block, expected, message) {
365 | var actual, ok = false;
366 |
367 | if (typeof expected === 'string') {
368 | message = expected;
369 | expected = null;
370 | }
371 |
372 | try {
373 | block();
374 | } catch (e) {
375 | actual = e;
376 | }
377 |
378 | if (actual) {
379 | // we don't want to validate thrown error
380 | if (!expected) {
381 | ok = true;
382 | // expected is a regexp
383 | } else if (QUnit.objectType(expected) === "regexp") {
384 | ok = expected.test(actual);
385 | // expected is a constructor
386 | } else if (actual instanceof expected) {
387 | ok = true;
388 | // expected is a validation function which returns true is validation passed
389 | } else if (expected.call({}, actual) === true) {
390 | ok = true;
391 | }
392 | }
393 |
394 | QUnit.ok(ok, message);
395 | },
396 |
397 | start: function(count) {
398 | config.semaphore -= count || 1;
399 | if (config.semaphore > 0) {
400 | // don't start until equal number of stop-calls
401 | return;
402 | }
403 | if (config.semaphore < 0) {
404 | // ignore if start is called more often then stop
405 | config.semaphore = 0;
406 | }
407 | // A slight delay, to avoid any current callbacks
408 | if ( defined.setTimeout ) {
409 | window.setTimeout(function() {
410 | if (config.semaphore > 0) {
411 | return;
412 | }
413 | if ( config.timeout ) {
414 | clearTimeout(config.timeout);
415 | }
416 |
417 | config.blocking = false;
418 | process(true);
419 | }, 13);
420 | } else {
421 | config.blocking = false;
422 | process(true);
423 | }
424 | },
425 |
426 | stop: function(count) {
427 | config.semaphore += count || 1;
428 | config.blocking = true;
429 |
430 | if ( config.testTimeout && defined.setTimeout ) {
431 | clearTimeout(config.timeout);
432 | config.timeout = window.setTimeout(function() {
433 | QUnit.ok( false, "Test timed out" );
434 | config.semaphore = 1;
435 | QUnit.start();
436 | }, config.testTimeout);
437 | }
438 | }
439 | };
440 |
441 | //We want access to the constructor's prototype
442 | (function() {
443 | function F(){};
444 | F.prototype = QUnit;
445 | QUnit = new F();
446 | //Make F QUnit's constructor so that we can add to the prototype later
447 | QUnit.constructor = F;
448 | })();
449 |
450 | // Backwards compatibility, deprecated
451 | QUnit.equals = QUnit.equal;
452 | QUnit.same = QUnit.deepEqual;
453 |
454 | // Maintain internal state
455 | var config = {
456 | // The queue of tests to run
457 | queue: [],
458 |
459 | // block until document ready
460 | blocking: true,
461 |
462 | // when enabled, show only failing tests
463 | // gets persisted through sessionStorage and can be changed in UI via checkbox
464 | hidepassed: false,
465 |
466 | // by default, run previously failed tests first
467 | // very useful in combination with "Hide passed tests" checked
468 | reorder: true,
469 |
470 | // by default, modify document.title when suite is done
471 | altertitle: true,
472 |
473 | urlConfig: ['noglobals', 'notrycatch'],
474 |
475 | //logging callback queues
476 | begin: [],
477 | done: [],
478 | log: [],
479 | testStart: [],
480 | testDone: [],
481 | moduleStart: [],
482 | moduleDone: []
483 | };
484 |
485 | // Load paramaters
486 | (function() {
487 | var location = window.location || { search: "", protocol: "file:" },
488 | params = location.search.slice( 1 ).split( "&" ),
489 | length = params.length,
490 | urlParams = {},
491 | current;
492 |
493 | if ( params[ 0 ] ) {
494 | for ( var i = 0; i < length; i++ ) {
495 | current = params[ i ].split( "=" );
496 | current[ 0 ] = decodeURIComponent( current[ 0 ] );
497 | // allow just a key to turn on a flag, e.g., test.html?noglobals
498 | current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
499 | urlParams[ current[ 0 ] ] = current[ 1 ];
500 | }
501 | }
502 |
503 | QUnit.urlParams = urlParams;
504 | config.filter = urlParams.filter;
505 |
506 | // Figure out if we're running the tests from a server or not
507 | QUnit.isLocal = !!(location.protocol === 'file:');
508 | })();
509 |
510 | // Expose the API as global variables, unless an 'exports'
511 | // object exists, in that case we assume we're in CommonJS
512 | if ( typeof exports === "undefined" || typeof require === "undefined" ) {
513 | extend(window, QUnit);
514 | window.QUnit = QUnit;
515 | } else {
516 | extend(exports, QUnit);
517 | exports.QUnit = QUnit;
518 | }
519 |
520 | // define these after exposing globals to keep them in these QUnit namespace only
521 | extend(QUnit, {
522 | config: config,
523 |
524 | // Initialize the configuration options
525 | init: function() {
526 | extend(config, {
527 | stats: { all: 0, bad: 0 },
528 | moduleStats: { all: 0, bad: 0 },
529 | started: +new Date,
530 | updateRate: 1000,
531 | blocking: false,
532 | autostart: true,
533 | autorun: false,
534 | filter: "",
535 | queue: [],
536 | semaphore: 0
537 | });
538 |
539 | var tests = id( "qunit-tests" ),
540 | banner = id( "qunit-banner" ),
541 | result = id( "qunit-testresult" );
542 |
543 | if ( tests ) {
544 | tests.innerHTML = "";
545 | }
546 |
547 | if ( banner ) {
548 | banner.className = "";
549 | }
550 |
551 | if ( result ) {
552 | result.parentNode.removeChild( result );
553 | }
554 |
555 | if ( tests ) {
556 | result = document.createElement( "p" );
557 | result.id = "qunit-testresult";
558 | result.className = "result";
559 | tests.parentNode.insertBefore( result, tests );
560 | result.innerHTML = 'Running... ';
561 | }
562 | },
563 |
564 | /**
565 | * Resets the test setup. Useful for tests that modify the DOM.
566 | *
567 | * If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
568 | */
569 | reset: function() {
570 | if ( window.jQuery ) {
571 | jQuery( "#qunit-fixture" ).html( config.fixture );
572 | } else {
573 | var main = id( 'qunit-fixture' );
574 | if ( main ) {
575 | main.innerHTML = config.fixture;
576 | }
577 | }
578 | },
579 |
580 | /**
581 | * Trigger an event on an element.
582 | *
583 | * @example triggerEvent( document.body, "click" );
584 | *
585 | * @param DOMElement elem
586 | * @param String type
587 | */
588 | triggerEvent: function( elem, type, event ) {
589 | if ( document.createEvent ) {
590 | event = document.createEvent("MouseEvents");
591 | event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
592 | 0, 0, 0, 0, 0, false, false, false, false, 0, null);
593 | elem.dispatchEvent( event );
594 |
595 | } else if ( elem.fireEvent ) {
596 | elem.fireEvent("on"+type);
597 | }
598 | },
599 |
600 | // Safe object type checking
601 | is: function( type, obj ) {
602 | return QUnit.objectType( obj ) == type;
603 | },
604 |
605 | objectType: function( obj ) {
606 | if (typeof obj === "undefined") {
607 | return "undefined";
608 |
609 | // consider: typeof null === object
610 | }
611 | if (obj === null) {
612 | return "null";
613 | }
614 |
615 | var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || '';
616 |
617 | switch (type) {
618 | case 'Number':
619 | if (isNaN(obj)) {
620 | return "nan";
621 | } else {
622 | return "number";
623 | }
624 | case 'String':
625 | case 'Boolean':
626 | case 'Array':
627 | case 'Date':
628 | case 'RegExp':
629 | case 'Function':
630 | return type.toLowerCase();
631 | }
632 | if (typeof obj === "object") {
633 | return "object";
634 | }
635 | return undefined;
636 | },
637 |
638 | push: function(result, actual, expected, message) {
639 | var details = {
640 | result: result,
641 | message: message,
642 | actual: actual,
643 | expected: expected
644 | };
645 |
646 | message = escapeInnerText(message) || (result ? "okay" : "failed");
647 | message = '' + message + " ";
648 | expected = escapeInnerText(QUnit.jsDump.parse(expected));
649 | actual = escapeInnerText(QUnit.jsDump.parse(actual));
650 | var output = message + 'Expected: ' + expected + ' ';
651 | if (actual != expected) {
652 | output += 'Result: ' + actual + ' ';
653 | output += 'Diff: ' + QUnit.diff(expected, actual) +' ';
654 | }
655 | if (!result) {
656 | var source = sourceFromStacktrace();
657 | if (source) {
658 | details.source = source;
659 | output += 'Source: ' + escapeInnerText(source) + ' ';
660 | }
661 | }
662 | output += "
";
663 |
664 | runLoggingCallbacks( 'log', QUnit, details );
665 |
666 | config.current.assertions.push({
667 | result: !!result,
668 | message: output
669 | });
670 | },
671 |
672 | url: function( params ) {
673 | params = extend( extend( {}, QUnit.urlParams ), params );
674 | var querystring = "?",
675 | key;
676 | for ( key in params ) {
677 | if ( !hasOwn.call( params, key ) ) {
678 | continue;
679 | }
680 | querystring += encodeURIComponent( key ) + "=" +
681 | encodeURIComponent( params[ key ] ) + "&";
682 | }
683 | return window.location.pathname + querystring.slice( 0, -1 );
684 | },
685 |
686 | extend: extend,
687 | id: id,
688 | addEvent: addEvent
689 | });
690 |
691 | //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later
692 | //Doing this allows us to tell if the following methods have been overwritten on the actual
693 | //QUnit object, which is a deprecated way of using the callbacks.
694 | extend(QUnit.constructor.prototype, {
695 | // Logging callbacks; all receive a single argument with the listed properties
696 | // run test/logs.html for any related changes
697 | begin: registerLoggingCallback('begin'),
698 | // done: { failed, passed, total, runtime }
699 | done: registerLoggingCallback('done'),
700 | // log: { result, actual, expected, message }
701 | log: registerLoggingCallback('log'),
702 | // testStart: { name }
703 | testStart: registerLoggingCallback('testStart'),
704 | // testDone: { name, failed, passed, total }
705 | testDone: registerLoggingCallback('testDone'),
706 | // moduleStart: { name }
707 | moduleStart: registerLoggingCallback('moduleStart'),
708 | // moduleDone: { name, failed, passed, total }
709 | moduleDone: registerLoggingCallback('moduleDone')
710 | });
711 |
712 | if ( typeof document === "undefined" || document.readyState === "complete" ) {
713 | config.autorun = true;
714 | }
715 |
716 | QUnit.load = function() {
717 | runLoggingCallbacks( 'begin', QUnit, {} );
718 |
719 | // Initialize the config, saving the execution queue
720 | var oldconfig = extend({}, config);
721 | QUnit.init();
722 | extend(config, oldconfig);
723 |
724 | config.blocking = false;
725 |
726 | var urlConfigHtml = '', len = config.urlConfig.length;
727 | for ( var i = 0, val; i < len, val = config.urlConfig[i]; i++ ) {
728 | config[val] = QUnit.urlParams[val];
729 | urlConfigHtml += ' ' + val + ' ';
730 | }
731 |
732 | var userAgent = id("qunit-userAgent");
733 | if ( userAgent ) {
734 | userAgent.innerHTML = navigator.userAgent;
735 | }
736 | var banner = id("qunit-header");
737 | if ( banner ) {
738 | banner.innerHTML = ' ' + banner.innerHTML + ' ' + urlConfigHtml;
739 | addEvent( banner, "change", function( event ) {
740 | var params = {};
741 | params[ event.target.name ] = event.target.checked ? true : undefined;
742 | window.location = QUnit.url( params );
743 | });
744 | }
745 |
746 | var toolbar = id("qunit-testrunner-toolbar");
747 | if ( toolbar ) {
748 | var filter = document.createElement("input");
749 | filter.type = "checkbox";
750 | filter.id = "qunit-filter-pass";
751 | addEvent( filter, "click", function() {
752 | var ol = document.getElementById("qunit-tests");
753 | if ( filter.checked ) {
754 | ol.className = ol.className + " hidepass";
755 | } else {
756 | var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
757 | ol.className = tmp.replace(/ hidepass /, " ");
758 | }
759 | if ( defined.sessionStorage ) {
760 | if (filter.checked) {
761 | sessionStorage.setItem("qunit-filter-passed-tests", "true");
762 | } else {
763 | sessionStorage.removeItem("qunit-filter-passed-tests");
764 | }
765 | }
766 | });
767 | if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) {
768 | filter.checked = true;
769 | var ol = document.getElementById("qunit-tests");
770 | ol.className = ol.className + " hidepass";
771 | }
772 | toolbar.appendChild( filter );
773 |
774 | var label = document.createElement("label");
775 | label.setAttribute("for", "qunit-filter-pass");
776 | label.innerHTML = "Hide passed tests";
777 | toolbar.appendChild( label );
778 | }
779 |
780 | var main = id('qunit-fixture');
781 | if ( main ) {
782 | config.fixture = main.innerHTML;
783 | }
784 |
785 | if (config.autostart) {
786 | QUnit.start();
787 | }
788 | };
789 |
790 | addEvent(window, "load", QUnit.load);
791 |
792 | // addEvent(window, "error") gives us a useless event object
793 | window.onerror = function( message, file, line ) {
794 | if ( QUnit.config.current ) {
795 | ok( false, message + ", " + file + ":" + line );
796 | } else {
797 | test( "global failure", function() {
798 | ok( false, message + ", " + file + ":" + line );
799 | });
800 | }
801 | };
802 |
803 | function done() {
804 | config.autorun = true;
805 |
806 | // Log the last module results
807 | if ( config.currentModule ) {
808 | runLoggingCallbacks( 'moduleDone', QUnit, {
809 | name: config.currentModule,
810 | failed: config.moduleStats.bad,
811 | passed: config.moduleStats.all - config.moduleStats.bad,
812 | total: config.moduleStats.all
813 | } );
814 | }
815 |
816 | var banner = id("qunit-banner"),
817 | tests = id("qunit-tests"),
818 | runtime = +new Date - config.started,
819 | passed = config.stats.all - config.stats.bad,
820 | html = [
821 | 'Tests completed in ',
822 | runtime,
823 | ' milliseconds. ',
824 | '',
825 | passed,
826 | ' tests of ',
827 | config.stats.all,
828 | ' passed, ',
829 | config.stats.bad,
830 | ' failed.'
831 | ].join('');
832 |
833 | if ( banner ) {
834 | banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass");
835 | }
836 |
837 | if ( tests ) {
838 | id( "qunit-testresult" ).innerHTML = html;
839 | }
840 |
841 | if ( config.altertitle && typeof document !== "undefined" && document.title ) {
842 | // show ✖ for good, ✔ for bad suite result in title
843 | // use escape sequences in case file gets loaded with non-utf-8-charset
844 | document.title = [
845 | (config.stats.bad ? "\u2716" : "\u2714"),
846 | document.title.replace(/^[\u2714\u2716] /i, "")
847 | ].join(" ");
848 | }
849 |
850 | runLoggingCallbacks( 'done', QUnit, {
851 | failed: config.stats.bad,
852 | passed: passed,
853 | total: config.stats.all,
854 | runtime: runtime
855 | } );
856 | }
857 |
858 | function validTest( name ) {
859 | var filter = config.filter,
860 | run = false;
861 |
862 | if ( !filter ) {
863 | return true;
864 | }
865 |
866 | var not = filter.charAt( 0 ) === "!";
867 | if ( not ) {
868 | filter = filter.slice( 1 );
869 | }
870 |
871 | if ( name.indexOf( filter ) !== -1 ) {
872 | return !not;
873 | }
874 |
875 | if ( not ) {
876 | run = true;
877 | }
878 |
879 | return run;
880 | }
881 |
882 | // so far supports only Firefox, Chrome and Opera (buggy)
883 | // could be extended in the future to use something like https://github.com/csnover/TraceKit
884 | function sourceFromStacktrace() {
885 | try {
886 | throw new Error();
887 | } catch ( e ) {
888 | if (e.stacktrace) {
889 | // Opera
890 | return e.stacktrace.split("\n")[6];
891 | } else if (e.stack) {
892 | // Firefox, Chrome
893 | return e.stack.split("\n")[4];
894 | } else if (e.sourceURL) {
895 | // Safari, PhantomJS
896 | // TODO sourceURL points at the 'throw new Error' line above, useless
897 | //return e.sourceURL + ":" + e.line;
898 | }
899 | }
900 | }
901 |
902 | function escapeInnerText(s) {
903 | if (!s) {
904 | return "";
905 | }
906 | s = s + "";
907 | return s.replace(/[\&<>]/g, function(s) {
908 | switch(s) {
909 | case "&": return "&";
910 | case "<": return "<";
911 | case ">": return ">";
912 | default: return s;
913 | }
914 | });
915 | }
916 |
917 | function synchronize( callback, last ) {
918 | config.queue.push( callback );
919 |
920 | if ( config.autorun && !config.blocking ) {
921 | process(last);
922 | }
923 | }
924 |
925 | function process( last ) {
926 | var start = new Date().getTime();
927 | config.depth = config.depth ? config.depth + 1 : 1;
928 |
929 | while ( config.queue.length && !config.blocking ) {
930 | if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
931 | config.queue.shift()();
932 | } else {
933 | window.setTimeout( function(){
934 | process( last );
935 | }, 13 );
936 | break;
937 | }
938 | }
939 | config.depth--;
940 | if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
941 | done();
942 | }
943 | }
944 |
945 | function saveGlobal() {
946 | config.pollution = [];
947 |
948 | if ( config.noglobals ) {
949 | for ( var key in window ) {
950 | if ( !hasOwn.call( window, key ) ) {
951 | continue;
952 | }
953 | config.pollution.push( key );
954 | }
955 | }
956 | }
957 |
958 | function checkPollution( name ) {
959 | var old = config.pollution;
960 | saveGlobal();
961 |
962 | var newGlobals = diff( config.pollution, old );
963 | if ( newGlobals.length > 0 ) {
964 | ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
965 | }
966 |
967 | var deletedGlobals = diff( old, config.pollution );
968 | if ( deletedGlobals.length > 0 ) {
969 | ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
970 | }
971 | }
972 |
973 | // returns a new Array with the elements that are in a but not in b
974 | function diff( a, b ) {
975 | var result = a.slice();
976 | for ( var i = 0; i < result.length; i++ ) {
977 | for ( var j = 0; j < b.length; j++ ) {
978 | if ( result[i] === b[j] ) {
979 | result.splice(i, 1);
980 | i--;
981 | break;
982 | }
983 | }
984 | }
985 | return result;
986 | }
987 |
988 | function fail(message, exception, callback) {
989 | if ( typeof console !== "undefined" && console.error && console.warn ) {
990 | console.error(message);
991 | console.error(exception);
992 | console.error(exception.stack);
993 | console.warn(callback.toString());
994 |
995 | } else if ( window.opera && opera.postError ) {
996 | opera.postError(message, exception, callback.toString);
997 | }
998 | }
999 |
1000 | function extend(a, b) {
1001 | for ( var prop in b ) {
1002 | if ( b[prop] === undefined ) {
1003 | delete a[prop];
1004 |
1005 | // Avoid "Member not found" error in IE8 caused by setting window.constructor
1006 | } else if ( prop !== "constructor" || a !== window ) {
1007 | a[prop] = b[prop];
1008 | }
1009 | }
1010 |
1011 | return a;
1012 | }
1013 |
1014 | function addEvent(elem, type, fn) {
1015 | if ( elem.addEventListener ) {
1016 | elem.addEventListener( type, fn, false );
1017 | } else if ( elem.attachEvent ) {
1018 | elem.attachEvent( "on" + type, fn );
1019 | } else {
1020 | fn();
1021 | }
1022 | }
1023 |
1024 | function id(name) {
1025 | return !!(typeof document !== "undefined" && document && document.getElementById) &&
1026 | document.getElementById( name );
1027 | }
1028 |
1029 | function registerLoggingCallback(key){
1030 | return function(callback){
1031 | config[key].push( callback );
1032 | };
1033 | }
1034 |
1035 | // Supports deprecated method of completely overwriting logging callbacks
1036 | function runLoggingCallbacks(key, scope, args) {
1037 | //debugger;
1038 | var callbacks;
1039 | if ( QUnit.hasOwnProperty(key) ) {
1040 | QUnit[key].call(scope, args);
1041 | } else {
1042 | callbacks = config[key];
1043 | for( var i = 0; i < callbacks.length; i++ ) {
1044 | callbacks[i].call( scope, args );
1045 | }
1046 | }
1047 | }
1048 |
1049 | // Test for equality any JavaScript type.
1050 | // Author: Philippe Rathé
1051 | QUnit.equiv = function () {
1052 |
1053 | var innerEquiv; // the real equiv function
1054 | var callers = []; // stack to decide between skip/abort functions
1055 | var parents = []; // stack to avoiding loops from circular referencing
1056 |
1057 | // Call the o related callback with the given arguments.
1058 | function bindCallbacks(o, callbacks, args) {
1059 | var prop = QUnit.objectType(o);
1060 | if (prop) {
1061 | if (QUnit.objectType(callbacks[prop]) === "function") {
1062 | return callbacks[prop].apply(callbacks, args);
1063 | } else {
1064 | return callbacks[prop]; // or undefined
1065 | }
1066 | }
1067 | }
1068 |
1069 | var getProto = Object.getPrototypeOf || function (obj) {
1070 | return obj.__proto__;
1071 | };
1072 |
1073 | var callbacks = function () {
1074 |
1075 | // for string, boolean, number and null
1076 | function useStrictEquality(b, a) {
1077 | if (b instanceof a.constructor || a instanceof b.constructor) {
1078 | // to catch short annotaion VS 'new' annotation of a
1079 | // declaration
1080 | // e.g. var i = 1;
1081 | // var j = new Number(1);
1082 | return a == b;
1083 | } else {
1084 | return a === b;
1085 | }
1086 | }
1087 |
1088 | return {
1089 | "string" : useStrictEquality,
1090 | "boolean" : useStrictEquality,
1091 | "number" : useStrictEquality,
1092 | "null" : useStrictEquality,
1093 | "undefined" : useStrictEquality,
1094 |
1095 | "nan" : function(b) {
1096 | return isNaN(b);
1097 | },
1098 |
1099 | "date" : function(b, a) {
1100 | return QUnit.objectType(b) === "date"
1101 | && a.valueOf() === b.valueOf();
1102 | },
1103 |
1104 | "regexp" : function(b, a) {
1105 | return QUnit.objectType(b) === "regexp"
1106 | && a.source === b.source && // the regex itself
1107 | a.global === b.global && // and its modifers
1108 | // (gmi) ...
1109 | a.ignoreCase === b.ignoreCase
1110 | && a.multiline === b.multiline;
1111 | },
1112 |
1113 | // - skip when the property is a method of an instance (OOP)
1114 | // - abort otherwise,
1115 | // initial === would have catch identical references anyway
1116 | "function" : function() {
1117 | var caller = callers[callers.length - 1];
1118 | return caller !== Object && typeof caller !== "undefined";
1119 | },
1120 |
1121 | "array" : function(b, a) {
1122 | var i, j, loop;
1123 | var len;
1124 |
1125 | // b could be an object literal here
1126 | if (!(QUnit.objectType(b) === "array")) {
1127 | return false;
1128 | }
1129 |
1130 | len = a.length;
1131 | if (len !== b.length) { // safe and faster
1132 | return false;
1133 | }
1134 |
1135 | // track reference to avoid circular references
1136 | parents.push(a);
1137 | for (i = 0; i < len; i++) {
1138 | loop = false;
1139 | for (j = 0; j < parents.length; j++) {
1140 | if (parents[j] === a[i]) {
1141 | loop = true;// dont rewalk array
1142 | }
1143 | }
1144 | if (!loop && !innerEquiv(a[i], b[i])) {
1145 | parents.pop();
1146 | return false;
1147 | }
1148 | }
1149 | parents.pop();
1150 | return true;
1151 | },
1152 |
1153 | "object" : function(b, a) {
1154 | var i, j, loop;
1155 | var eq = true; // unless we can proove it
1156 | var aProperties = [], bProperties = []; // collection of
1157 | // strings
1158 |
1159 | // comparing constructors is more strict than using
1160 | // instanceof
1161 | if (a.constructor !== b.constructor) {
1162 | // Allow objects with no prototype to be equivalent to
1163 | // objects with Object as their constructor.
1164 | if (!((getProto(a) === null && getProto(b) === Object.prototype) ||
1165 | (getProto(b) === null && getProto(a) === Object.prototype)))
1166 | {
1167 | return false;
1168 | }
1169 | }
1170 |
1171 | // stack constructor before traversing properties
1172 | callers.push(a.constructor);
1173 | // track reference to avoid circular references
1174 | parents.push(a);
1175 |
1176 | for (i in a) { // be strict: don't ensures hasOwnProperty
1177 | // and go deep
1178 | loop = false;
1179 | for (j = 0; j < parents.length; j++) {
1180 | if (parents[j] === a[i])
1181 | loop = true; // don't go down the same path
1182 | // twice
1183 | }
1184 | aProperties.push(i); // collect a's properties
1185 |
1186 | if (!loop && !innerEquiv(a[i], b[i])) {
1187 | eq = false;
1188 | break;
1189 | }
1190 | }
1191 |
1192 | callers.pop(); // unstack, we are done
1193 | parents.pop();
1194 |
1195 | for (i in b) {
1196 | bProperties.push(i); // collect b's properties
1197 | }
1198 |
1199 | // Ensures identical properties name
1200 | return eq
1201 | && innerEquiv(aProperties.sort(), bProperties
1202 | .sort());
1203 | }
1204 | };
1205 | }();
1206 |
1207 | innerEquiv = function() { // can take multiple arguments
1208 | var args = Array.prototype.slice.apply(arguments);
1209 | if (args.length < 2) {
1210 | return true; // end transition
1211 | }
1212 |
1213 | return (function(a, b) {
1214 | if (a === b) {
1215 | return true; // catch the most you can
1216 | } else if (a === null || b === null || typeof a === "undefined"
1217 | || typeof b === "undefined"
1218 | || QUnit.objectType(a) !== QUnit.objectType(b)) {
1219 | return false; // don't lose time with error prone cases
1220 | } else {
1221 | return bindCallbacks(a, callbacks, [ b, a ]);
1222 | }
1223 |
1224 | // apply transition with (1..n) arguments
1225 | })(args[0], args[1])
1226 | && arguments.callee.apply(this, args.splice(1,
1227 | args.length - 1));
1228 | };
1229 |
1230 | return innerEquiv;
1231 |
1232 | }();
1233 |
1234 | /**
1235 | * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
1236 | * http://flesler.blogspot.com Licensed under BSD
1237 | * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
1238 | *
1239 | * @projectDescription Advanced and extensible data dumping for Javascript.
1240 | * @version 1.0.0
1241 | * @author Ariel Flesler
1242 | * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
1243 | */
1244 | QUnit.jsDump = (function() {
1245 | function quote( str ) {
1246 | return '"' + str.toString().replace(/"/g, '\\"') + '"';
1247 | };
1248 | function literal( o ) {
1249 | return o + '';
1250 | };
1251 | function join( pre, arr, post ) {
1252 | var s = jsDump.separator(),
1253 | base = jsDump.indent(),
1254 | inner = jsDump.indent(1);
1255 | if ( arr.join )
1256 | arr = arr.join( ',' + s + inner );
1257 | if ( !arr )
1258 | return pre + post;
1259 | return [ pre, inner + arr, base + post ].join(s);
1260 | };
1261 | function array( arr, stack ) {
1262 | var i = arr.length, ret = Array(i);
1263 | this.up();
1264 | while ( i-- )
1265 | ret[i] = this.parse( arr[i] , undefined , stack);
1266 | this.down();
1267 | return join( '[', ret, ']' );
1268 | };
1269 |
1270 | var reName = /^function (\w+)/;
1271 |
1272 | var jsDump = {
1273 | parse:function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance
1274 | stack = stack || [ ];
1275 | var parser = this.parsers[ type || this.typeOf(obj) ];
1276 | type = typeof parser;
1277 | var inStack = inArray(obj, stack);
1278 | if (inStack != -1) {
1279 | return 'recursion('+(inStack - stack.length)+')';
1280 | }
1281 | //else
1282 | if (type == 'function') {
1283 | stack.push(obj);
1284 | var res = parser.call( this, obj, stack );
1285 | stack.pop();
1286 | return res;
1287 | }
1288 | // else
1289 | return (type == 'string') ? parser : this.parsers.error;
1290 | },
1291 | typeOf:function( obj ) {
1292 | var type;
1293 | if ( obj === null ) {
1294 | type = "null";
1295 | } else if (typeof obj === "undefined") {
1296 | type = "undefined";
1297 | } else if (QUnit.is("RegExp", obj)) {
1298 | type = "regexp";
1299 | } else if (QUnit.is("Date", obj)) {
1300 | type = "date";
1301 | } else if (QUnit.is("Function", obj)) {
1302 | type = "function";
1303 | } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") {
1304 | type = "window";
1305 | } else if (obj.nodeType === 9) {
1306 | type = "document";
1307 | } else if (obj.nodeType) {
1308 | type = "node";
1309 | } else if (
1310 | // native arrays
1311 | toString.call( obj ) === "[object Array]" ||
1312 | // NodeList objects
1313 | ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
1314 | ) {
1315 | type = "array";
1316 | } else {
1317 | type = typeof obj;
1318 | }
1319 | return type;
1320 | },
1321 | separator:function() {
1322 | return this.multiline ? this.HTML ? ' ' : '\n' : this.HTML ? ' ' : ' ';
1323 | },
1324 | indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
1325 | if ( !this.multiline )
1326 | return '';
1327 | var chr = this.indentChar;
1328 | if ( this.HTML )
1329 | chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
1330 | return Array( this._depth_ + (extra||0) ).join(chr);
1331 | },
1332 | up:function( a ) {
1333 | this._depth_ += a || 1;
1334 | },
1335 | down:function( a ) {
1336 | this._depth_ -= a || 1;
1337 | },
1338 | setParser:function( name, parser ) {
1339 | this.parsers[name] = parser;
1340 | },
1341 | // The next 3 are exposed so you can use them
1342 | quote:quote,
1343 | literal:literal,
1344 | join:join,
1345 | //
1346 | _depth_: 1,
1347 | // This is the list of parsers, to modify them, use jsDump.setParser
1348 | parsers:{
1349 | window: '[Window]',
1350 | document: '[Document]',
1351 | error:'[ERROR]', //when no parser is found, shouldn't happen
1352 | unknown: '[Unknown]',
1353 | 'null':'null',
1354 | 'undefined':'undefined',
1355 | 'function':function( fn ) {
1356 | var ret = 'function',
1357 | name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
1358 | if ( name )
1359 | ret += ' ' + name;
1360 | ret += '(';
1361 |
1362 | ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join('');
1363 | return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' );
1364 | },
1365 | array: array,
1366 | nodelist: array,
1367 | arguments: array,
1368 | object:function( map, stack ) {
1369 | var ret = [ ];
1370 | QUnit.jsDump.up();
1371 | for ( var key in map ) {
1372 | var val = map[key];
1373 | ret.push( QUnit.jsDump.parse(key,'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack));
1374 | }
1375 | QUnit.jsDump.down();
1376 | return join( '{', ret, '}' );
1377 | },
1378 | node:function( node ) {
1379 | var open = QUnit.jsDump.HTML ? '<' : '<',
1380 | close = QUnit.jsDump.HTML ? '>' : '>';
1381 |
1382 | var tag = node.nodeName.toLowerCase(),
1383 | ret = open + tag;
1384 |
1385 | for ( var a in QUnit.jsDump.DOMAttrs ) {
1386 | var val = node[QUnit.jsDump.DOMAttrs[a]];
1387 | if ( val )
1388 | ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' );
1389 | }
1390 | return ret + close + open + '/' + tag + close;
1391 | },
1392 | functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
1393 | var l = fn.length;
1394 | if ( !l ) return '';
1395 |
1396 | var args = Array(l);
1397 | while ( l-- )
1398 | args[l] = String.fromCharCode(97+l);//97 is 'a'
1399 | return ' ' + args.join(', ') + ' ';
1400 | },
1401 | key:quote, //object calls it internally, the key part of an item in a map
1402 | functionCode:'[code]', //function calls it internally, it's the content of the function
1403 | attribute:quote, //node calls it internally, it's an html attribute value
1404 | string:quote,
1405 | date:quote,
1406 | regexp:literal, //regex
1407 | number:literal,
1408 | 'boolean':literal
1409 | },
1410 | DOMAttrs:{//attributes to dump from nodes, name=>realName
1411 | id:'id',
1412 | name:'name',
1413 | 'class':'className'
1414 | },
1415 | HTML:false,//if true, entities are escaped ( <, >, \t, space and \n )
1416 | indentChar:' ',//indentation unit
1417 | multiline:true //if true, items in a collection, are separated by a \n, else just a space.
1418 | };
1419 |
1420 | return jsDump;
1421 | })();
1422 |
1423 | // from Sizzle.js
1424 | function getText( elems ) {
1425 | var ret = "", elem;
1426 |
1427 | for ( var i = 0; elems[i]; i++ ) {
1428 | elem = elems[i];
1429 |
1430 | // Get the text from text nodes and CDATA nodes
1431 | if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
1432 | ret += elem.nodeValue;
1433 |
1434 | // Traverse everything else, except comment nodes
1435 | } else if ( elem.nodeType !== 8 ) {
1436 | ret += getText( elem.childNodes );
1437 | }
1438 | }
1439 |
1440 | return ret;
1441 | };
1442 |
1443 | //from jquery.js
1444 | function inArray( elem, array ) {
1445 | if ( array.indexOf ) {
1446 | return array.indexOf( elem );
1447 | }
1448 |
1449 | for ( var i = 0, length = array.length; i < length; i++ ) {
1450 | if ( array[ i ] === elem ) {
1451 | return i;
1452 | }
1453 | }
1454 |
1455 | return -1;
1456 | }
1457 |
1458 | /*
1459 | * Javascript Diff Algorithm
1460 | * By John Resig (http://ejohn.org/)
1461 | * Modified by Chu Alan "sprite"
1462 | *
1463 | * Released under the MIT license.
1464 | *
1465 | * More Info:
1466 | * http://ejohn.org/projects/javascript-diff-algorithm/
1467 | *
1468 | * Usage: QUnit.diff(expected, actual)
1469 | *
1470 | * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick brown fox jumped jumps over"
1471 | */
1472 | QUnit.diff = (function() {
1473 | function diff(o, n) {
1474 | var ns = {};
1475 | var os = {};
1476 |
1477 | for (var i = 0; i < n.length; i++) {
1478 | if (ns[n[i]] == null)
1479 | ns[n[i]] = {
1480 | rows: [],
1481 | o: null
1482 | };
1483 | ns[n[i]].rows.push(i);
1484 | }
1485 |
1486 | for (var i = 0; i < o.length; i++) {
1487 | if (os[o[i]] == null)
1488 | os[o[i]] = {
1489 | rows: [],
1490 | n: null
1491 | };
1492 | os[o[i]].rows.push(i);
1493 | }
1494 |
1495 | for (var i in ns) {
1496 | if ( !hasOwn.call( ns, i ) ) {
1497 | continue;
1498 | }
1499 | if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
1500 | n[ns[i].rows[0]] = {
1501 | text: n[ns[i].rows[0]],
1502 | row: os[i].rows[0]
1503 | };
1504 | o[os[i].rows[0]] = {
1505 | text: o[os[i].rows[0]],
1506 | row: ns[i].rows[0]
1507 | };
1508 | }
1509 | }
1510 |
1511 | for (var i = 0; i < n.length - 1; i++) {
1512 | if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null &&
1513 | n[i + 1] == o[n[i].row + 1]) {
1514 | n[i + 1] = {
1515 | text: n[i + 1],
1516 | row: n[i].row + 1
1517 | };
1518 | o[n[i].row + 1] = {
1519 | text: o[n[i].row + 1],
1520 | row: i + 1
1521 | };
1522 | }
1523 | }
1524 |
1525 | for (var i = n.length - 1; i > 0; i--) {
1526 | if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
1527 | n[i - 1] == o[n[i].row - 1]) {
1528 | n[i - 1] = {
1529 | text: n[i - 1],
1530 | row: n[i].row - 1
1531 | };
1532 | o[n[i].row - 1] = {
1533 | text: o[n[i].row - 1],
1534 | row: i - 1
1535 | };
1536 | }
1537 | }
1538 |
1539 | return {
1540 | o: o,
1541 | n: n
1542 | };
1543 | }
1544 |
1545 | return function(o, n) {
1546 | o = o.replace(/\s+$/, '');
1547 | n = n.replace(/\s+$/, '');
1548 | var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/));
1549 |
1550 | var str = "";
1551 |
1552 | var oSpace = o.match(/\s+/g);
1553 | if (oSpace == null) {
1554 | oSpace = [" "];
1555 | }
1556 | else {
1557 | oSpace.push(" ");
1558 | }
1559 | var nSpace = n.match(/\s+/g);
1560 | if (nSpace == null) {
1561 | nSpace = [" "];
1562 | }
1563 | else {
1564 | nSpace.push(" ");
1565 | }
1566 |
1567 | if (out.n.length == 0) {
1568 | for (var i = 0; i < out.o.length; i++) {
1569 | str += '' + out.o[i] + oSpace[i] + "";
1570 | }
1571 | }
1572 | else {
1573 | if (out.n[0].text == null) {
1574 | for (n = 0; n < out.o.length && out.o[n].text == null; n++) {
1575 | str += '' + out.o[n] + oSpace[n] + "";
1576 | }
1577 | }
1578 |
1579 | for (var i = 0; i < out.n.length; i++) {
1580 | if (out.n[i].text == null) {
1581 | str += '' + out.n[i] + nSpace[i] + " ";
1582 | }
1583 | else {
1584 | var pre = "";
1585 |
1586 | for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) {
1587 | pre += '' + out.o[n] + oSpace[n] + "";
1588 | }
1589 | str += " " + out.n[i].text + nSpace[i] + pre;
1590 | }
1591 | }
1592 | }
1593 |
1594 | return str;
1595 | };
1596 | })();
1597 |
1598 | })(this);
1599 |
--------------------------------------------------------------------------------
/tests/vendor/underscore.js:
--------------------------------------------------------------------------------
1 | // Underscore.js 1.4.2
2 | // http://underscorejs.org
3 | // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
4 | // Underscore may be freely distributed under the MIT license.
5 |
6 | (function() {
7 |
8 | // Baseline setup
9 | // --------------
10 |
11 | // Establish the root object, `window` in the browser, or `global` on the server.
12 | var root = this;
13 |
14 | // Save the previous value of the `_` variable.
15 | var previousUnderscore = root._;
16 |
17 | // Establish the object that gets returned to break out of a loop iteration.
18 | var breaker = {};
19 |
20 | // Save bytes in the minified (but not gzipped) version:
21 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
22 |
23 | // Create quick reference variables for speed access to core prototypes.
24 | var push = ArrayProto.push,
25 | slice = ArrayProto.slice,
26 | concat = ArrayProto.concat,
27 | unshift = ArrayProto.unshift,
28 | toString = ObjProto.toString,
29 | hasOwnProperty = ObjProto.hasOwnProperty;
30 |
31 | // All **ECMAScript 5** native function implementations that we hope to use
32 | // are declared here.
33 | var
34 | nativeForEach = ArrayProto.forEach,
35 | nativeMap = ArrayProto.map,
36 | nativeReduce = ArrayProto.reduce,
37 | nativeReduceRight = ArrayProto.reduceRight,
38 | nativeFilter = ArrayProto.filter,
39 | nativeEvery = ArrayProto.every,
40 | nativeSome = ArrayProto.some,
41 | nativeIndexOf = ArrayProto.indexOf,
42 | nativeLastIndexOf = ArrayProto.lastIndexOf,
43 | nativeIsArray = Array.isArray,
44 | nativeKeys = Object.keys,
45 | nativeBind = FuncProto.bind;
46 |
47 | // Create a safe reference to the Underscore object for use below.
48 | var _ = function(obj) {
49 | if (obj instanceof _) return obj;
50 | if (!(this instanceof _)) return new _(obj);
51 | this._wrapped = obj;
52 | };
53 |
54 | // Export the Underscore object for **Node.js**, with
55 | // backwards-compatibility for the old `require()` API. If we're in
56 | // the browser, add `_` as a global object via a string identifier,
57 | // for Closure Compiler "advanced" mode.
58 | if (typeof exports !== 'undefined') {
59 | if (typeof module !== 'undefined' && module.exports) {
60 | exports = module.exports = _;
61 | }
62 | exports._ = _;
63 | } else {
64 | root['_'] = _;
65 | }
66 |
67 | // Current version.
68 | _.VERSION = '1.4.2';
69 |
70 | // Collection Functions
71 | // --------------------
72 |
73 | // The cornerstone, an `each` implementation, aka `forEach`.
74 | // Handles objects with the built-in `forEach`, arrays, and raw objects.
75 | // Delegates to **ECMAScript 5**'s native `forEach` if available.
76 | var each = _.each = _.forEach = function(obj, iterator, context) {
77 | if (obj == null) return;
78 | if (nativeForEach && obj.forEach === nativeForEach) {
79 | obj.forEach(iterator, context);
80 | } else if (obj.length === +obj.length) {
81 | for (var i = 0, l = obj.length; i < l; i++) {
82 | if (iterator.call(context, obj[i], i, obj) === breaker) return;
83 | }
84 | } else {
85 | for (var key in obj) {
86 | if (_.has(obj, key)) {
87 | if (iterator.call(context, obj[key], key, obj) === breaker) return;
88 | }
89 | }
90 | }
91 | };
92 |
93 | // Return the results of applying the iterator to each element.
94 | // Delegates to **ECMAScript 5**'s native `map` if available.
95 | _.map = _.collect = function(obj, iterator, context) {
96 | var results = [];
97 | if (obj == null) return results;
98 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
99 | each(obj, function(value, index, list) {
100 | results[results.length] = iterator.call(context, value, index, list);
101 | });
102 | return results;
103 | };
104 |
105 | // **Reduce** builds up a single result from a list of values, aka `inject`,
106 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
107 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
108 | var initial = arguments.length > 2;
109 | if (obj == null) obj = [];
110 | if (nativeReduce && obj.reduce === nativeReduce) {
111 | if (context) iterator = _.bind(iterator, context);
112 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
113 | }
114 | each(obj, function(value, index, list) {
115 | if (!initial) {
116 | memo = value;
117 | initial = true;
118 | } else {
119 | memo = iterator.call(context, memo, value, index, list);
120 | }
121 | });
122 | if (!initial) throw new TypeError('Reduce of empty array with no initial value');
123 | return memo;
124 | };
125 |
126 | // The right-associative version of reduce, also known as `foldr`.
127 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
128 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
129 | var initial = arguments.length > 2;
130 | if (obj == null) obj = [];
131 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
132 | if (context) iterator = _.bind(iterator, context);
133 | return arguments.length > 2 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
134 | }
135 | var length = obj.length;
136 | if (length !== +length) {
137 | var keys = _.keys(obj);
138 | length = keys.length;
139 | }
140 | each(obj, function(value, index, list) {
141 | index = keys ? keys[--length] : --length;
142 | if (!initial) {
143 | memo = obj[index];
144 | initial = true;
145 | } else {
146 | memo = iterator.call(context, memo, obj[index], index, list);
147 | }
148 | });
149 | if (!initial) throw new TypeError('Reduce of empty array with no initial value');
150 | return memo;
151 | };
152 |
153 | // Return the first value which passes a truth test. Aliased as `detect`.
154 | _.find = _.detect = function(obj, iterator, context) {
155 | var result;
156 | any(obj, function(value, index, list) {
157 | if (iterator.call(context, value, index, list)) {
158 | result = value;
159 | return true;
160 | }
161 | });
162 | return result;
163 | };
164 |
165 | // Return all the elements that pass a truth test.
166 | // Delegates to **ECMAScript 5**'s native `filter` if available.
167 | // Aliased as `select`.
168 | _.filter = _.select = function(obj, iterator, context) {
169 | var results = [];
170 | if (obj == null) return results;
171 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
172 | each(obj, function(value, index, list) {
173 | if (iterator.call(context, value, index, list)) results[results.length] = value;
174 | });
175 | return results;
176 | };
177 |
178 | // Return all the elements for which a truth test fails.
179 | _.reject = function(obj, iterator, context) {
180 | var results = [];
181 | if (obj == null) return results;
182 | each(obj, function(value, index, list) {
183 | if (!iterator.call(context, value, index, list)) results[results.length] = value;
184 | });
185 | return results;
186 | };
187 |
188 | // Determine whether all of the elements match a truth test.
189 | // Delegates to **ECMAScript 5**'s native `every` if available.
190 | // Aliased as `all`.
191 | _.every = _.all = function(obj, iterator, context) {
192 | iterator || (iterator = _.identity);
193 | var result = true;
194 | if (obj == null) return result;
195 | if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
196 | each(obj, function(value, index, list) {
197 | if (!(result = result && iterator.call(context, value, index, list))) return breaker;
198 | });
199 | return !!result;
200 | };
201 |
202 | // Determine if at least one element in the object matches a truth test.
203 | // Delegates to **ECMAScript 5**'s native `some` if available.
204 | // Aliased as `any`.
205 | var any = _.some = _.any = function(obj, iterator, context) {
206 | iterator || (iterator = _.identity);
207 | var result = false;
208 | if (obj == null) return result;
209 | if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
210 | each(obj, function(value, index, list) {
211 | if (result || (result = iterator.call(context, value, index, list))) return breaker;
212 | });
213 | return !!result;
214 | };
215 |
216 | // Determine if the array or object contains a given value (using `===`).
217 | // Aliased as `include`.
218 | _.contains = _.include = function(obj, target) {
219 | var found = false;
220 | if (obj == null) return found;
221 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
222 | found = any(obj, function(value) {
223 | return value === target;
224 | });
225 | return found;
226 | };
227 |
228 | // Invoke a method (with arguments) on every item in a collection.
229 | _.invoke = function(obj, method) {
230 | var args = slice.call(arguments, 2);
231 | return _.map(obj, function(value) {
232 | return (_.isFunction(method) ? method : value[method]).apply(value, args);
233 | });
234 | };
235 |
236 | // Convenience version of a common use case of `map`: fetching a property.
237 | _.pluck = function(obj, key) {
238 | return _.map(obj, function(value){ return value[key]; });
239 | };
240 |
241 | // Convenience version of a common use case of `filter`: selecting only objects
242 | // with specific `key:value` pairs.
243 | _.where = function(obj, attrs) {
244 | if (_.isEmpty(attrs)) return [];
245 | return _.filter(obj, function(value) {
246 | for (var key in attrs) {
247 | if (attrs[key] !== value[key]) return false;
248 | }
249 | return true;
250 | });
251 | };
252 |
253 | // Return the maximum element or (element-based computation).
254 | // Can't optimize arrays of integers longer than 65,535 elements.
255 | // See: https://bugs.webkit.org/show_bug.cgi?id=80797
256 | _.max = function(obj, iterator, context) {
257 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
258 | return Math.max.apply(Math, obj);
259 | }
260 | if (!iterator && _.isEmpty(obj)) return -Infinity;
261 | var result = {computed : -Infinity};
262 | each(obj, function(value, index, list) {
263 | var computed = iterator ? iterator.call(context, value, index, list) : value;
264 | computed >= result.computed && (result = {value : value, computed : computed});
265 | });
266 | return result.value;
267 | };
268 |
269 | // Return the minimum element (or element-based computation).
270 | _.min = function(obj, iterator, context) {
271 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
272 | return Math.min.apply(Math, obj);
273 | }
274 | if (!iterator && _.isEmpty(obj)) return Infinity;
275 | var result = {computed : Infinity};
276 | each(obj, function(value, index, list) {
277 | var computed = iterator ? iterator.call(context, value, index, list) : value;
278 | computed < result.computed && (result = {value : value, computed : computed});
279 | });
280 | return result.value;
281 | };
282 |
283 | // Shuffle an array.
284 | _.shuffle = function(obj) {
285 | var rand;
286 | var index = 0;
287 | var shuffled = [];
288 | each(obj, function(value) {
289 | rand = _.random(index++);
290 | shuffled[index - 1] = shuffled[rand];
291 | shuffled[rand] = value;
292 | });
293 | return shuffled;
294 | };
295 |
296 | // An internal function to generate lookup iterators.
297 | var lookupIterator = function(value) {
298 | return _.isFunction(value) ? value : function(obj){ return obj[value]; };
299 | };
300 |
301 | // Sort the object's values by a criterion produced by an iterator.
302 | _.sortBy = function(obj, value, context) {
303 | var iterator = lookupIterator(value);
304 | return _.pluck(_.map(obj, function(value, index, list) {
305 | return {
306 | value : value,
307 | index : index,
308 | criteria : iterator.call(context, value, index, list)
309 | };
310 | }).sort(function(left, right) {
311 | var a = left.criteria;
312 | var b = right.criteria;
313 | if (a !== b) {
314 | if (a > b || a === void 0) return 1;
315 | if (a < b || b === void 0) return -1;
316 | }
317 | return left.index < right.index ? -1 : 1;
318 | }), 'value');
319 | };
320 |
321 | // An internal function used for aggregate "group by" operations.
322 | var group = function(obj, value, context, behavior) {
323 | var result = {};
324 | var iterator = lookupIterator(value);
325 | each(obj, function(value, index) {
326 | var key = iterator.call(context, value, index, obj);
327 | behavior(result, key, value);
328 | });
329 | return result;
330 | };
331 |
332 | // Groups the object's values by a criterion. Pass either a string attribute
333 | // to group by, or a function that returns the criterion.
334 | _.groupBy = function(obj, value, context) {
335 | return group(obj, value, context, function(result, key, value) {
336 | (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
337 | });
338 | };
339 |
340 | // Counts instances of an object that group by a certain criterion. Pass
341 | // either a string attribute to count by, or a function that returns the
342 | // criterion.
343 | _.countBy = function(obj, value, context) {
344 | return group(obj, value, context, function(result, key, value) {
345 | if (!_.has(result, key)) result[key] = 0;
346 | result[key]++;
347 | });
348 | };
349 |
350 | // Use a comparator function to figure out the smallest index at which
351 | // an object should be inserted so as to maintain order. Uses binary search.
352 | _.sortedIndex = function(array, obj, iterator, context) {
353 | iterator = iterator == null ? _.identity : lookupIterator(iterator);
354 | var value = iterator.call(context, obj);
355 | var low = 0, high = array.length;
356 | while (low < high) {
357 | var mid = (low + high) >>> 1;
358 | iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
359 | }
360 | return low;
361 | };
362 |
363 | // Safely convert anything iterable into a real, live array.
364 | _.toArray = function(obj) {
365 | if (!obj) return [];
366 | if (obj.length === +obj.length) return slice.call(obj);
367 | return _.values(obj);
368 | };
369 |
370 | // Return the number of elements in an object.
371 | _.size = function(obj) {
372 | return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
373 | };
374 |
375 | // Array Functions
376 | // ---------------
377 |
378 | // Get the first element of an array. Passing **n** will return the first N
379 | // values in the array. Aliased as `head` and `take`. The **guard** check
380 | // allows it to work with `_.map`.
381 | _.first = _.head = _.take = function(array, n, guard) {
382 | return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
383 | };
384 |
385 | // Returns everything but the last entry of the array. Especially useful on
386 | // the arguments object. Passing **n** will return all the values in
387 | // the array, excluding the last N. The **guard** check allows it to work with
388 | // `_.map`.
389 | _.initial = function(array, n, guard) {
390 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
391 | };
392 |
393 | // Get the last element of an array. Passing **n** will return the last N
394 | // values in the array. The **guard** check allows it to work with `_.map`.
395 | _.last = function(array, n, guard) {
396 | if ((n != null) && !guard) {
397 | return slice.call(array, Math.max(array.length - n, 0));
398 | } else {
399 | return array[array.length - 1];
400 | }
401 | };
402 |
403 | // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
404 | // Especially useful on the arguments object. Passing an **n** will return
405 | // the rest N values in the array. The **guard**
406 | // check allows it to work with `_.map`.
407 | _.rest = _.tail = _.drop = function(array, n, guard) {
408 | return slice.call(array, (n == null) || guard ? 1 : n);
409 | };
410 |
411 | // Trim out all falsy values from an array.
412 | _.compact = function(array) {
413 | return _.filter(array, function(value){ return !!value; });
414 | };
415 |
416 | // Internal implementation of a recursive `flatten` function.
417 | var flatten = function(input, shallow, output) {
418 | each(input, function(value) {
419 | if (_.isArray(value)) {
420 | shallow ? push.apply(output, value) : flatten(value, shallow, output);
421 | } else {
422 | output.push(value);
423 | }
424 | });
425 | return output;
426 | };
427 |
428 | // Return a completely flattened version of an array.
429 | _.flatten = function(array, shallow) {
430 | return flatten(array, shallow, []);
431 | };
432 |
433 | // Return a version of the array that does not contain the specified value(s).
434 | _.without = function(array) {
435 | return _.difference(array, slice.call(arguments, 1));
436 | };
437 |
438 | // Produce a duplicate-free version of the array. If the array has already
439 | // been sorted, you have the option of using a faster algorithm.
440 | // Aliased as `unique`.
441 | _.uniq = _.unique = function(array, isSorted, iterator, context) {
442 | var initial = iterator ? _.map(array, iterator, context) : array;
443 | var results = [];
444 | var seen = [];
445 | each(initial, function(value, index) {
446 | if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
447 | seen.push(value);
448 | results.push(array[index]);
449 | }
450 | });
451 | return results;
452 | };
453 |
454 | // Produce an array that contains the union: each distinct element from all of
455 | // the passed-in arrays.
456 | _.union = function() {
457 | return _.uniq(concat.apply(ArrayProto, arguments));
458 | };
459 |
460 | // Produce an array that contains every item shared between all the
461 | // passed-in arrays.
462 | _.intersection = function(array) {
463 | var rest = slice.call(arguments, 1);
464 | return _.filter(_.uniq(array), function(item) {
465 | return _.every(rest, function(other) {
466 | return _.indexOf(other, item) >= 0;
467 | });
468 | });
469 | };
470 |
471 | // Take the difference between one array and a number of other arrays.
472 | // Only the elements present in just the first array will remain.
473 | _.difference = function(array) {
474 | var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
475 | return _.filter(array, function(value){ return !_.contains(rest, value); });
476 | };
477 |
478 | // Zip together multiple lists into a single array -- elements that share
479 | // an index go together.
480 | _.zip = function() {
481 | var args = slice.call(arguments);
482 | var length = _.max(_.pluck(args, 'length'));
483 | var results = new Array(length);
484 | for (var i = 0; i < length; i++) {
485 | results[i] = _.pluck(args, "" + i);
486 | }
487 | return results;
488 | };
489 |
490 | // Converts lists into objects. Pass either a single array of `[key, value]`
491 | // pairs, or two parallel arrays of the same length -- one of keys, and one of
492 | // the corresponding values.
493 | _.object = function(list, values) {
494 | var result = {};
495 | for (var i = 0, l = list.length; i < l; i++) {
496 | if (values) {
497 | result[list[i]] = values[i];
498 | } else {
499 | result[list[i][0]] = list[i][1];
500 | }
501 | }
502 | return result;
503 | };
504 |
505 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
506 | // we need this function. Return the position of the first occurrence of an
507 | // item in an array, or -1 if the item is not included in the array.
508 | // Delegates to **ECMAScript 5**'s native `indexOf` if available.
509 | // If the array is large and already in sort order, pass `true`
510 | // for **isSorted** to use binary search.
511 | _.indexOf = function(array, item, isSorted) {
512 | if (array == null) return -1;
513 | var i = 0, l = array.length;
514 | if (isSorted) {
515 | if (typeof isSorted == 'number') {
516 | i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
517 | } else {
518 | i = _.sortedIndex(array, item);
519 | return array[i] === item ? i : -1;
520 | }
521 | }
522 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
523 | for (; i < l; i++) if (array[i] === item) return i;
524 | return -1;
525 | };
526 |
527 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
528 | _.lastIndexOf = function(array, item, from) {
529 | if (array == null) return -1;
530 | var hasIndex = from != null;
531 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
532 | return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
533 | }
534 | var i = (hasIndex ? from : array.length);
535 | while (i--) if (array[i] === item) return i;
536 | return -1;
537 | };
538 |
539 | // Generate an integer Array containing an arithmetic progression. A port of
540 | // the native Python `range()` function. See
541 | // [the Python documentation](http://docs.python.org/library/functions.html#range).
542 | _.range = function(start, stop, step) {
543 | if (arguments.length <= 1) {
544 | stop = start || 0;
545 | start = 0;
546 | }
547 | step = arguments[2] || 1;
548 |
549 | var len = Math.max(Math.ceil((stop - start) / step), 0);
550 | var idx = 0;
551 | var range = new Array(len);
552 |
553 | while(idx < len) {
554 | range[idx++] = start;
555 | start += step;
556 | }
557 |
558 | return range;
559 | };
560 |
561 | // Function (ahem) Functions
562 | // ------------------
563 |
564 | // Reusable constructor function for prototype setting.
565 | var ctor = function(){};
566 |
567 | // Create a function bound to a given object (assigning `this`, and arguments,
568 | // optionally). Binding with arguments is also known as `curry`.
569 | // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
570 | // We check for `func.bind` first, to fail fast when `func` is undefined.
571 | _.bind = function bind(func, context) {
572 | var bound, args;
573 | if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
574 | if (!_.isFunction(func)) throw new TypeError;
575 | args = slice.call(arguments, 2);
576 | return bound = function() {
577 | if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
578 | ctor.prototype = func.prototype;
579 | var self = new ctor;
580 | var result = func.apply(self, args.concat(slice.call(arguments)));
581 | if (Object(result) === result) return result;
582 | return self;
583 | };
584 | };
585 |
586 | // Bind all of an object's methods to that object. Useful for ensuring that
587 | // all callbacks defined on an object belong to it.
588 | _.bindAll = function(obj) {
589 | var funcs = slice.call(arguments, 1);
590 | if (funcs.length == 0) funcs = _.functions(obj);
591 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
592 | return obj;
593 | };
594 |
595 | // Memoize an expensive function by storing its results.
596 | _.memoize = function(func, hasher) {
597 | var memo = {};
598 | hasher || (hasher = _.identity);
599 | return function() {
600 | var key = hasher.apply(this, arguments);
601 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
602 | };
603 | };
604 |
605 | // Delays a function for the given number of milliseconds, and then calls
606 | // it with the arguments supplied.
607 | _.delay = function(func, wait) {
608 | var args = slice.call(arguments, 2);
609 | return setTimeout(function(){ return func.apply(null, args); }, wait);
610 | };
611 |
612 | // Defers a function, scheduling it to run after the current call stack has
613 | // cleared.
614 | _.defer = function(func) {
615 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
616 | };
617 |
618 | // Returns a function, that, when invoked, will only be triggered at most once
619 | // during a given window of time.
620 | _.throttle = function(func, wait) {
621 | var context, args, timeout, throttling, more, result;
622 | var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
623 | return function() {
624 | context = this; args = arguments;
625 | var later = function() {
626 | timeout = null;
627 | if (more) {
628 | result = func.apply(context, args);
629 | }
630 | whenDone();
631 | };
632 | if (!timeout) timeout = setTimeout(later, wait);
633 | if (throttling) {
634 | more = true;
635 | } else {
636 | throttling = true;
637 | result = func.apply(context, args);
638 | }
639 | whenDone();
640 | return result;
641 | };
642 | };
643 |
644 | // Returns a function, that, as long as it continues to be invoked, will not
645 | // be triggered. The function will be called after it stops being called for
646 | // N milliseconds. If `immediate` is passed, trigger the function on the
647 | // leading edge, instead of the trailing.
648 | _.debounce = function(func, wait, immediate) {
649 | var timeout, result;
650 | return function() {
651 | var context = this, args = arguments;
652 | var later = function() {
653 | timeout = null;
654 | if (!immediate) result = func.apply(context, args);
655 | };
656 | var callNow = immediate && !timeout;
657 | clearTimeout(timeout);
658 | timeout = setTimeout(later, wait);
659 | if (callNow) result = func.apply(context, args);
660 | return result;
661 | };
662 | };
663 |
664 | // Returns a function that will be executed at most one time, no matter how
665 | // often you call it. Useful for lazy initialization.
666 | _.once = function(func) {
667 | var ran = false, memo;
668 | return function() {
669 | if (ran) return memo;
670 | ran = true;
671 | memo = func.apply(this, arguments);
672 | func = null;
673 | return memo;
674 | };
675 | };
676 |
677 | // Returns the first function passed as an argument to the second,
678 | // allowing you to adjust arguments, run code before and after, and
679 | // conditionally execute the original function.
680 | _.wrap = function(func, wrapper) {
681 | return function() {
682 | var args = [func];
683 | push.apply(args, arguments);
684 | return wrapper.apply(this, args);
685 | };
686 | };
687 |
688 | // Returns a function that is the composition of a list of functions, each
689 | // consuming the return value of the function that follows.
690 | _.compose = function() {
691 | var funcs = arguments;
692 | return function() {
693 | var args = arguments;
694 | for (var i = funcs.length - 1; i >= 0; i--) {
695 | args = [funcs[i].apply(this, args)];
696 | }
697 | return args[0];
698 | };
699 | };
700 |
701 | // Returns a function that will only be executed after being called N times.
702 | _.after = function(times, func) {
703 | if (times <= 0) return func();
704 | return function() {
705 | if (--times < 1) {
706 | return func.apply(this, arguments);
707 | }
708 | };
709 | };
710 |
711 | // Object Functions
712 | // ----------------
713 |
714 | // Retrieve the names of an object's properties.
715 | // Delegates to **ECMAScript 5**'s native `Object.keys`
716 | _.keys = nativeKeys || function(obj) {
717 | if (obj !== Object(obj)) throw new TypeError('Invalid object');
718 | var keys = [];
719 | for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
720 | return keys;
721 | };
722 |
723 | // Retrieve the values of an object's properties.
724 | _.values = function(obj) {
725 | var values = [];
726 | for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
727 | return values;
728 | };
729 |
730 | // Convert an object into a list of `[key, value]` pairs.
731 | _.pairs = function(obj) {
732 | var pairs = [];
733 | for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
734 | return pairs;
735 | };
736 |
737 | // Invert the keys and values of an object. The values must be serializable.
738 | _.invert = function(obj) {
739 | var result = {};
740 | for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
741 | return result;
742 | };
743 |
744 | // Return a sorted list of the function names available on the object.
745 | // Aliased as `methods`
746 | _.functions = _.methods = function(obj) {
747 | var names = [];
748 | for (var key in obj) {
749 | if (_.isFunction(obj[key])) names.push(key);
750 | }
751 | return names.sort();
752 | };
753 |
754 | // Extend a given object with all the properties in passed-in object(s).
755 | _.extend = function(obj) {
756 | each(slice.call(arguments, 1), function(source) {
757 | for (var prop in source) {
758 | obj[prop] = source[prop];
759 | }
760 | });
761 | return obj;
762 | };
763 |
764 | // Return a copy of the object only containing the whitelisted properties.
765 | _.pick = function(obj) {
766 | var copy = {};
767 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
768 | each(keys, function(key) {
769 | if (key in obj) copy[key] = obj[key];
770 | });
771 | return copy;
772 | };
773 |
774 | // Return a copy of the object without the blacklisted properties.
775 | _.omit = function(obj) {
776 | var copy = {};
777 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
778 | for (var key in obj) {
779 | if (!_.contains(keys, key)) copy[key] = obj[key];
780 | }
781 | return copy;
782 | };
783 |
784 | // Fill in a given object with default properties.
785 | _.defaults = function(obj) {
786 | each(slice.call(arguments, 1), function(source) {
787 | for (var prop in source) {
788 | if (obj[prop] == null) obj[prop] = source[prop];
789 | }
790 | });
791 | return obj;
792 | };
793 |
794 | // Create a (shallow-cloned) duplicate of an object.
795 | _.clone = function(obj) {
796 | if (!_.isObject(obj)) return obj;
797 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
798 | };
799 |
800 | // Invokes interceptor with the obj, and then returns obj.
801 | // The primary purpose of this method is to "tap into" a method chain, in
802 | // order to perform operations on intermediate results within the chain.
803 | _.tap = function(obj, interceptor) {
804 | interceptor(obj);
805 | return obj;
806 | };
807 |
808 | // Internal recursive comparison function for `isEqual`.
809 | var eq = function(a, b, aStack, bStack) {
810 | // Identical objects are equal. `0 === -0`, but they aren't identical.
811 | // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
812 | if (a === b) return a !== 0 || 1 / a == 1 / b;
813 | // A strict comparison is necessary because `null == undefined`.
814 | if (a == null || b == null) return a === b;
815 | // Unwrap any wrapped objects.
816 | if (a instanceof _) a = a._wrapped;
817 | if (b instanceof _) b = b._wrapped;
818 | // Compare `[[Class]]` names.
819 | var className = toString.call(a);
820 | if (className != toString.call(b)) return false;
821 | switch (className) {
822 | // Strings, numbers, dates, and booleans are compared by value.
823 | case '[object String]':
824 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
825 | // equivalent to `new String("5")`.
826 | return a == String(b);
827 | case '[object Number]':
828 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
829 | // other numeric values.
830 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
831 | case '[object Date]':
832 | case '[object Boolean]':
833 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their
834 | // millisecond representations. Note that invalid dates with millisecond representations
835 | // of `NaN` are not equivalent.
836 | return +a == +b;
837 | // RegExps are compared by their source patterns and flags.
838 | case '[object RegExp]':
839 | return a.source == b.source &&
840 | a.global == b.global &&
841 | a.multiline == b.multiline &&
842 | a.ignoreCase == b.ignoreCase;
843 | }
844 | if (typeof a != 'object' || typeof b != 'object') return false;
845 | // Assume equality for cyclic structures. The algorithm for detecting cyclic
846 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
847 | var length = aStack.length;
848 | while (length--) {
849 | // Linear search. Performance is inversely proportional to the number of
850 | // unique nested structures.
851 | if (aStack[length] == a) return bStack[length] == b;
852 | }
853 | // Add the first object to the stack of traversed objects.
854 | aStack.push(a);
855 | bStack.push(b);
856 | var size = 0, result = true;
857 | // Recursively compare objects and arrays.
858 | if (className == '[object Array]') {
859 | // Compare array lengths to determine if a deep comparison is necessary.
860 | size = a.length;
861 | result = size == b.length;
862 | if (result) {
863 | // Deep compare the contents, ignoring non-numeric properties.
864 | while (size--) {
865 | if (!(result = eq(a[size], b[size], aStack, bStack))) break;
866 | }
867 | }
868 | } else {
869 | // Objects with different constructors are not equivalent, but `Object`s
870 | // from different frames are.
871 | var aCtor = a.constructor, bCtor = b.constructor;
872 | if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
873 | _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
874 | return false;
875 | }
876 | // Deep compare objects.
877 | for (var key in a) {
878 | if (_.has(a, key)) {
879 | // Count the expected number of properties.
880 | size++;
881 | // Deep compare each member.
882 | if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
883 | }
884 | }
885 | // Ensure that both objects contain the same number of properties.
886 | if (result) {
887 | for (key in b) {
888 | if (_.has(b, key) && !(size--)) break;
889 | }
890 | result = !size;
891 | }
892 | }
893 | // Remove the first object from the stack of traversed objects.
894 | aStack.pop();
895 | bStack.pop();
896 | return result;
897 | };
898 |
899 | // Perform a deep comparison to check if two objects are equal.
900 | _.isEqual = function(a, b) {
901 | return eq(a, b, [], []);
902 | };
903 |
904 | // Is a given array, string, or object empty?
905 | // An "empty" object has no enumerable own-properties.
906 | _.isEmpty = function(obj) {
907 | if (obj == null) return true;
908 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
909 | for (var key in obj) if (_.has(obj, key)) return false;
910 | return true;
911 | };
912 |
913 | // Is a given value a DOM element?
914 | _.isElement = function(obj) {
915 | return !!(obj && obj.nodeType === 1);
916 | };
917 |
918 | // Is a given value an array?
919 | // Delegates to ECMA5's native Array.isArray
920 | _.isArray = nativeIsArray || function(obj) {
921 | return toString.call(obj) == '[object Array]';
922 | };
923 |
924 | // Is a given variable an object?
925 | _.isObject = function(obj) {
926 | return obj === Object(obj);
927 | };
928 |
929 | // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
930 | each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
931 | _['is' + name] = function(obj) {
932 | return toString.call(obj) == '[object ' + name + ']';
933 | };
934 | });
935 |
936 | // Define a fallback version of the method in browsers (ahem, IE), where
937 | // there isn't any inspectable "Arguments" type.
938 | if (!_.isArguments(arguments)) {
939 | _.isArguments = function(obj) {
940 | return !!(obj && _.has(obj, 'callee'));
941 | };
942 | }
943 |
944 | // Optimize `isFunction` if appropriate.
945 | if (typeof (/./) !== 'function') {
946 | _.isFunction = function(obj) {
947 | return typeof obj === 'function';
948 | };
949 | }
950 |
951 | // Is a given object a finite number?
952 | _.isFinite = function(obj) {
953 | return _.isNumber(obj) && isFinite(obj);
954 | };
955 |
956 | // Is the given value `NaN`? (NaN is the only number which does not equal itself).
957 | _.isNaN = function(obj) {
958 | return _.isNumber(obj) && obj != +obj;
959 | };
960 |
961 | // Is a given value a boolean?
962 | _.isBoolean = function(obj) {
963 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
964 | };
965 |
966 | // Is a given value equal to null?
967 | _.isNull = function(obj) {
968 | return obj === null;
969 | };
970 |
971 | // Is a given variable undefined?
972 | _.isUndefined = function(obj) {
973 | return obj === void 0;
974 | };
975 |
976 | // Shortcut function for checking if an object has a given property directly
977 | // on itself (in other words, not on a prototype).
978 | _.has = function(obj, key) {
979 | return hasOwnProperty.call(obj, key);
980 | };
981 |
982 | // Utility Functions
983 | // -----------------
984 |
985 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
986 | // previous owner. Returns a reference to the Underscore object.
987 | _.noConflict = function() {
988 | root._ = previousUnderscore;
989 | return this;
990 | };
991 |
992 | // Keep the identity function around for default iterators.
993 | _.identity = function(value) {
994 | return value;
995 | };
996 |
997 | // Run a function **n** times.
998 | _.times = function(n, iterator, context) {
999 | for (var i = 0; i < n; i++) iterator.call(context, i);
1000 | };
1001 |
1002 | // Return a random integer between min and max (inclusive).
1003 | _.random = function(min, max) {
1004 | if (max == null) {
1005 | max = min;
1006 | min = 0;
1007 | }
1008 | return min + (0 | Math.random() * (max - min + 1));
1009 | };
1010 |
1011 | // List of HTML entities for escaping.
1012 | var entityMap = {
1013 | escape: {
1014 | '&': '&',
1015 | '<': '<',
1016 | '>': '>',
1017 | '"': '"',
1018 | "'": ''',
1019 | '/': '/'
1020 | }
1021 | };
1022 | entityMap.unescape = _.invert(entityMap.escape);
1023 |
1024 | // Regexes containing the keys and values listed immediately above.
1025 | var entityRegexes = {
1026 | escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
1027 | unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
1028 | };
1029 |
1030 | // Functions for escaping and unescaping strings to/from HTML interpolation.
1031 | _.each(['escape', 'unescape'], function(method) {
1032 | _[method] = function(string) {
1033 | if (string == null) return '';
1034 | return ('' + string).replace(entityRegexes[method], function(match) {
1035 | return entityMap[method][match];
1036 | });
1037 | };
1038 | });
1039 |
1040 | // If the value of the named property is a function then invoke it;
1041 | // otherwise, return it.
1042 | _.result = function(object, property) {
1043 | if (object == null) return null;
1044 | var value = object[property];
1045 | return _.isFunction(value) ? value.call(object) : value;
1046 | };
1047 |
1048 | // Add your own custom functions to the Underscore object.
1049 | _.mixin = function(obj) {
1050 | each(_.functions(obj), function(name){
1051 | var func = _[name] = obj[name];
1052 | _.prototype[name] = function() {
1053 | var args = [this._wrapped];
1054 | push.apply(args, arguments);
1055 | return result.call(this, func.apply(_, args));
1056 | };
1057 | });
1058 | };
1059 |
1060 | // Generate a unique integer id (unique within the entire client session).
1061 | // Useful for temporary DOM ids.
1062 | var idCounter = 0;
1063 | _.uniqueId = function(prefix) {
1064 | var id = idCounter++;
1065 | return prefix ? prefix + id : id;
1066 | };
1067 |
1068 | // By default, Underscore uses ERB-style template delimiters, change the
1069 | // following template settings to use alternative delimiters.
1070 | _.templateSettings = {
1071 | evaluate : /<%([\s\S]+?)%>/g,
1072 | interpolate : /<%=([\s\S]+?)%>/g,
1073 | escape : /<%-([\s\S]+?)%>/g
1074 | };
1075 |
1076 | // When customizing `templateSettings`, if you don't want to define an
1077 | // interpolation, evaluation or escaping regex, we need one that is
1078 | // guaranteed not to match.
1079 | var noMatch = /(.)^/;
1080 |
1081 | // Certain characters need to be escaped so that they can be put into a
1082 | // string literal.
1083 | var escapes = {
1084 | "'": "'",
1085 | '\\': '\\',
1086 | '\r': 'r',
1087 | '\n': 'n',
1088 | '\t': 't',
1089 | '\u2028': 'u2028',
1090 | '\u2029': 'u2029'
1091 | };
1092 |
1093 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
1094 |
1095 | // JavaScript micro-templating, similar to John Resig's implementation.
1096 | // Underscore templating handles arbitrary delimiters, preserves whitespace,
1097 | // and correctly escapes quotes within interpolated code.
1098 | _.template = function(text, data, settings) {
1099 | settings = _.defaults({}, settings, _.templateSettings);
1100 |
1101 | // Combine delimiters into one regular expression via alternation.
1102 | var matcher = new RegExp([
1103 | (settings.escape || noMatch).source,
1104 | (settings.interpolate || noMatch).source,
1105 | (settings.evaluate || noMatch).source
1106 | ].join('|') + '|$', 'g');
1107 |
1108 | // Compile the template source, escaping string literals appropriately.
1109 | var index = 0;
1110 | var source = "__p+='";
1111 | text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
1112 | source += text.slice(index, offset)
1113 | .replace(escaper, function(match) { return '\\' + escapes[match]; });
1114 | source +=
1115 | escape ? "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'" :
1116 | interpolate ? "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'" :
1117 | evaluate ? "';\n" + evaluate + "\n__p+='" : '';
1118 | index = offset + match.length;
1119 | });
1120 | source += "';\n";
1121 |
1122 | // If a variable is not specified, place data values in local scope.
1123 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1124 |
1125 | source = "var __t,__p='',__j=Array.prototype.join," +
1126 | "print=function(){__p+=__j.call(arguments,'');};\n" +
1127 | source + "return __p;\n";
1128 |
1129 | try {
1130 | var render = new Function(settings.variable || 'obj', '_', source);
1131 | } catch (e) {
1132 | e.source = source;
1133 | throw e;
1134 | }
1135 |
1136 | if (data) return render(data, _);
1137 | var template = function(data) {
1138 | return render.call(this, data, _);
1139 | };
1140 |
1141 | // Provide the compiled function source as a convenience for precompilation.
1142 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
1143 |
1144 | return template;
1145 | };
1146 |
1147 | // Add a "chain" function, which will delegate to the wrapper.
1148 | _.chain = function(obj) {
1149 | return _(obj).chain();
1150 | };
1151 |
1152 | // OOP
1153 | // ---------------
1154 | // If Underscore is called as a function, it returns a wrapped object that
1155 | // can be used OO-style. This wrapper holds altered versions of all the
1156 | // underscore functions. Wrapped objects may be chained.
1157 |
1158 | // Helper function to continue chaining intermediate results.
1159 | var result = function(obj) {
1160 | return this._chain ? _(obj).chain() : obj;
1161 | };
1162 |
1163 | // Add all of the Underscore functions to the wrapper object.
1164 | _.mixin(_);
1165 |
1166 | // Add all mutator Array functions to the wrapper.
1167 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1168 | var method = ArrayProto[name];
1169 | _.prototype[name] = function() {
1170 | var obj = this._wrapped;
1171 | method.apply(obj, arguments);
1172 | if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
1173 | return result.call(this, obj);
1174 | };
1175 | });
1176 |
1177 | // Add all accessor Array functions to the wrapper.
1178 | each(['concat', 'join', 'slice'], function(name) {
1179 | var method = ArrayProto[name];
1180 | _.prototype[name] = function() {
1181 | return result.call(this, method.apply(this._wrapped, arguments));
1182 | };
1183 | });
1184 |
1185 | _.extend(_.prototype, {
1186 |
1187 | // Start chaining a wrapped Underscore object.
1188 | chain: function() {
1189 | this._chain = true;
1190 | return this;
1191 | },
1192 |
1193 | // Extracts the result from a wrapped and chained object.
1194 | value: function() {
1195 | return this._wrapped;
1196 | }
1197 |
1198 | });
1199 |
1200 | }).call(this);
--------------------------------------------------------------------------------