├── .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 |

Backbone.Analytics Test Suite

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.$('