PageRenderTime 35ms CodeModel.GetById 2ms app.highlight 27ms RepoModel.GetById 1ms app.codeStats 0ms

/support/backbone.js

https://github.com/akshayrawat/DirectoryOfMPs
JavaScript | 685 lines | 433 code | 80 blank | 172 comment | 125 complexity | ec898b443d80a49b580eaaeada2b62ab MD5 | raw file
  1//     (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
  2//     Backbone may be freely distributed under the MIT license.
  3//     For all details and documentation:
  4//     http://documentcloud.github.com/backbone
  5
  6(function(){
  7
  8  // Initial Setup
  9  // -------------
 10
 11  // The top-level namespace. All public Backbone classes and modules will
 12  // be attached to this. Exported for both CommonJS and the browser.
 13  var Backbone;
 14  if (typeof exports !== 'undefined') {
 15    Backbone = exports;
 16  } else {
 17    Backbone = this.Backbone = {};
 18  }
 19
 20  // Current version of the library. Keep in sync with `package.json`.
 21  Backbone.VERSION = '0.1.2';
 22
 23  // Require Underscore, if we're on the server, and it's not already present.
 24  var _ = this._;
 25  if (!_ && (typeof require !== 'undefined')) _ = require("underscore")._;
 26
 27  // For Backbone's purposes, jQuery owns the `$` variable.
 28  var $ = this.jQuery;
 29
 30  // Turn on `emulateHttp` to fake `"PUT"` and `"DELETE"` requests via
 31  // the `_method` parameter.
 32  Backbone.emulateHttp = false;
 33
 34  // Backbone.Events
 35  // -----------------
 36
 37  // A module that can be mixed in to *any object* in order to provide it with
 38  // custom events. You may `bind` or `unbind` a callback function to an event;
 39  // `trigger`-ing an event fires all callbacks in succession.
 40  //
 41  //     var object = {};
 42  //     _.extend(object, Backbone.Events);
 43  //     object.bind('expand', function(){ alert('expanded'); });
 44  //     object.trigger('expand');
 45  //
 46  Backbone.Events = {
 47
 48    // Bind an event, specified by a string name, `ev`, to a `callback` function.
 49    // Passing `"all"` will bind the callback to all events fired.
 50    bind : function(ev, callback) {
 51      var calls = this._callbacks || (this._callbacks = {});
 52      var list  = this._callbacks[ev] || (this._callbacks[ev] = []);
 53      list.push(callback);
 54      return this;
 55    },
 56
 57    // Remove one or many callbacks. If `callback` is null, removes all
 58    // callbacks for the event. If `ev` is null, removes all bound callbacks
 59    // for all events.
 60    unbind : function(ev, callback) {
 61      var calls;
 62      if (!ev) {
 63        this._callbacks = {};
 64      } else if (calls = this._callbacks) {
 65        if (!callback) {
 66          calls[ev] = [];
 67        } else {
 68          var list = calls[ev];
 69          if (!list) return this;
 70          for (var i = 0, l = list.length; i < l; i++) {
 71            if (callback === list[i]) {
 72              list.splice(i, 1);
 73              break;
 74            }
 75          }
 76        }
 77      }
 78      return this;
 79    },
 80
 81    // Trigger an event, firing all bound callbacks. Callbacks are passed the
 82    // same arguments as `trigger` is, apart from the event name.
 83    // Listening for `"all"` passes the true event name as the first argument.
 84    trigger : function(ev) {
 85      var list, calls, i, l;
 86      if (!(calls = this._callbacks)) return this;
 87      if (list = calls[ev]) {
 88        for (i = 0, l = list.length; i < l; i++) {
 89          list[i].apply(this, Array.prototype.slice.call(arguments, 1));
 90        }
 91      }
 92      if (list = calls['all']) {
 93        for (i = 0, l = list.length; i < l; i++) {
 94          list[i].apply(this, arguments);
 95        }
 96      }
 97      return this;
 98    }
 99
100  };
101
102  // Backbone.Model
103  // --------------
104
105  // Create a new model, with defined attributes. A client id (`cid`)
106  // is automatically generated and assigned for you.
107  Backbone.Model = function(attributes) {
108    this.attributes = {};
109    this.cid = _.uniqueId('c');
110    this.set(attributes || {}, {silent : true});
111    this._previousAttributes = _.clone(this.attributes);
112    if (this.initialize) this.initialize(attributes);
113  };
114
115  // Attach all inheritable methods to the Model prototype.
116  _.extend(Backbone.Model.prototype, Backbone.Events, {
117
118    // A snapshot of the model's previous attributes, taken immediately
119    // after the last `"change"` event was fired.
120    _previousAttributes : null,
121
122    // Has the item been changed since the last `"change"` event?
123    _changed : false,
124
125    // Return a copy of the model's `attributes` object.
126    toJSON : function() {
127      return _.clone(this.attributes);
128    },
129
130    // Get the value of an attribute.
131    get : function(attr) {
132      return this.attributes[attr];
133    },
134
135    // Set a hash of model attributes on the object, firing `"change"` unless you
136    // choose to silence it.
137    set : function(attrs, options) {
138
139      // Extract attributes and options.
140      options || (options = {});
141      if (!attrs) return this;
142      if (attrs.attributes) attrs = attrs.attributes;
143      var now = this.attributes;
144
145      // Run validation if `validate` is defined. If a specific `error` callback
146      // has been passed, call that instead of firing the general `"error"` event.
147      if (this.validate) {
148        var error = this.validate(attrs);
149        if (error) {
150          if (options.error) {
151            options.error(this, error);
152          } else {
153            this.trigger('error', this, error);
154          }
155          return false;
156        }
157      }
158
159      // Check for changes of `id`.
160      if ('id' in attrs) this.id = attrs.id;
161
162      // Update attributes.
163      for (var attr in attrs) {
164        var val = attrs[attr];
165        if (val === '') val = null;
166        if (!_.isEqual(now[attr], val)) {
167          now[attr] = val;
168          if (!options.silent) {
169            this._changed = true;
170            this.trigger('change:' + attr, this, val);
171          }
172        }
173      }
174
175      // Fire the `"change"` event, if the model has been changed.
176      if (!options.silent && this._changed) this.change();
177      return this;
178    },
179
180    // Remove an attribute from the model, firing `"change"` unless you choose to
181    // silence it.
182    unset : function(attr, options) {
183      options || (options = {});
184      var value = this.attributes[attr];
185      delete this.attributes[attr];
186      if (!options.silent) {
187        this._changed = true;
188        this.trigger('change:' + attr, this);
189        this.change();
190      }
191      return value;
192    },
193
194    // Fetch the model from the server. If the server's representation of the
195    // model differs from its current attributes, they will be overriden,
196    // triggering a `"change"` event.
197    fetch : function(options) {
198      options || (options = {});
199      var model = this;
200      var success = function(resp) {
201        if (!model.set(resp.model, options)) return false;
202        if (options.success) options.success(model, resp);
203      };
204      var error = options.error && _.bind(options.error, null, model);
205      Backbone.sync('read', this, success, error);
206      return this;
207    },
208
209    // Set a hash of model attributes, and sync the model to the server.
210    // If the server returns an attributes hash that differs, the model's
211    // state will be `set` again.
212    save : function(attrs, options) {
213      attrs   || (attrs = {});
214      options || (options = {});
215      if (!this.set(attrs, options)) return false;
216      var model = this;
217      var success = function(resp) {
218        if (!model.set(resp.model, options)) return false;
219        if (options.success) options.success(model, resp);
220      };
221      var error = options.error && _.bind(options.error, null, model);
222      var method = this.isNew() ? 'create' : 'update';
223      Backbone.sync(method, this, success, error);
224      return this;
225    },
226
227    // Destroy this model on the server. Upon success, the model is removed
228    // from its collection, if it has one.
229    destroy : function(options) {
230      options || (options = {});
231      var model = this;
232      var success = function(resp) {
233        if (model.collection) model.collection.remove(model);
234        if (options.success) options.success(model, resp);
235      };
236      var error = options.error && _.bind(options.error, null, model);
237      Backbone.sync('delete', this, success, error);
238      return this;
239    },
240
241    // Default URL for the model's representation on the server -- if you're
242    // using Backbone's restful methods, override this to change the endpoint
243    // that will be called.
244    url : function() {
245      var base = getUrl(this.collection);
246      if (this.isNew()) return base;
247      return base + '/' + this.id;
248    },
249
250    // Create a new model with identical attributes to this one.
251    clone : function() {
252      return new this.constructor(this);
253    },
254
255    // A model is new if it has never been saved to the server, and has a negative
256    // ID.
257    isNew : function() {
258      return !this.id;
259    },
260
261    // Call this method to fire manually fire a `change` event for this model.
262    // Calling this will cause all objects observing the model to update.
263    change : function() {
264      this.trigger('change', this);
265      this._previousAttributes = _.clone(this.attributes);
266      this._changed = false;
267    },
268
269    // Determine if the model has changed since the last `"change"` event.
270    // If you specify an attribute name, determine if that attribute has changed.
271    hasChanged : function(attr) {
272      if (attr) return this._previousAttributes[attr] != this.attributes[attr];
273      return this._changed;
274    },
275
276    // Return an object containing all the attributes that have changed, or false
277    // if there are no changed attributes. Useful for determining what parts of a
278    // view need to be updated and/or what attributes need to be persisted to
279    // the server.
280    changedAttributes : function(now) {
281      now || (now = this.attributes);
282      var old = this._previousAttributes;
283      var changed = false;
284      for (var attr in now) {
285        if (!_.isEqual(old[attr], now[attr])) {
286          changed = changed || {};
287          changed[attr] = now[attr];
288        }
289      }
290      return changed;
291    },
292
293    // Get the previous value of an attribute, recorded at the time the last
294    // `"change"` event was fired.
295    previous : function(attr) {
296      if (!attr || !this._previousAttributes) return null;
297      return this._previousAttributes[attr];
298    },
299
300    // Get all of the attributes of the model at the time of the previous
301    // `"change"` event.
302    previousAttributes : function() {
303      return _.clone(this._previousAttributes);
304    }
305
306  });
307
308  // Backbone.Collection
309  // -------------------
310
311  // Provides a standard collection class for our sets of models, ordered
312  // or unordered. If a `comparator` is specified, the Collection will maintain
313  // its models in sort order, as they're added and removed.
314  Backbone.Collection = function(models, options) {
315    options || (options = {});
316    if (options.comparator) {
317      this.comparator = options.comparator;
318      delete options.comparator;
319    }
320    this._boundOnModelEvent = _.bind(this._onModelEvent, this);
321    this._reset();
322    if (models) this.refresh(models, {silent: true});
323    if (this.initialize) this.initialize(models, options);
324  };
325
326  // Define the Collection's inheritable methods.
327  _.extend(Backbone.Collection.prototype, Backbone.Events, {
328
329    // The default model for a collection is just a **Backbone.Model**.
330    // This should be overridden in most cases.
331    model : Backbone.Model,
332
333    // Add a model, or list of models to the set. Pass **silent** to avoid
334    // firing the `added` event for every new model.
335    add : function(models, options) {
336      if (_.isArray(models)) {
337        for (var i = 0, l = models.length; i < l; i++) {
338          this._add(models[i], options);
339        }
340      } else {
341        this._add(models, options);
342      }
343      return this;
344    },
345
346    // Remove a model, or a list of models from the set. Pass silent to avoid
347    // firing the `removed` event for every model removed.
348    remove : function(models, options) {
349      if (_.isArray(models)) {
350        for (var i = 0, l = models.length; i < l; i++) {
351          this._remove(models[i], options);
352        }
353      } else {
354        this._remove(models, options);
355      }
356      return this;
357    },
358
359    // Get a model from the set by id.
360    get : function(id) {
361      return id && this._byId[id.id != null ? id.id : id];
362    },
363
364    // Get a model from the set by client id.
365    getByCid : function(cid) {
366      return cid && this._byCid[cid.cid || cid];
367    },
368
369    // Get the model at the given index.
370    at: function(index) {
371      return this.models[index];
372    },
373
374    // Force the collection to re-sort itself. You don't need to call this under normal
375    // circumstances, as the set will maintain sort order as each item is added.
376    sort : function(options) {
377      options || (options = {});
378      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
379      this.models = this.sortBy(this.comparator);
380      if (!options.silent) this.trigger('refresh', this);
381      return this;
382    },
383
384    // Pluck an attribute from each model in the collection.
385    pluck : function(attr) {
386      return _.map(this.models, function(model){ return model.get(attr); });
387    },
388
389    // When you have more items than you want to add or remove individually,
390    // you can refresh the entire set with a new list of models, without firing
391    // any `added` or `removed` events. Fires `refresh` when finished.
392    refresh : function(models, options) {
393      models  || (models = []);
394      options || (options = {});
395      this._reset();
396      this.add(models, {silent: true});
397      if (!options.silent) this.trigger('refresh', this);
398      return this;
399    },
400
401    // Fetch the default set of models for this collection, refreshing the
402    // collection when they arrive.
403    fetch : function(options) {
404      options || (options = {});
405      var collection = this;
406      var success = function(resp) {
407        collection.refresh(resp.models);
408        if (options.success) options.success(collection, resp);
409      };
410      var error = options.error && _.bind(options.error, null, collection);
411      Backbone.sync('read', this, success, error);
412      return this;
413    },
414
415    // Create a new instance of a model in this collection. After the model
416    // has been created on the server, it will be added to the collection.
417    create : function(model, options) {
418      options || (options = {});
419      if (!(model instanceof Backbone.Model)) model = new this.model(model);
420      model.collection = this;
421      var success = function(resp) {
422        model.collection.add(model);
423        if (options.success) options.success(model, resp);
424      };
425      return model.save(null, {success : success, error : options.error});
426    },
427
428    // Reset all internal state. Called when the collection is refreshed.
429    _reset : function(options) {
430      this.length = 0;
431      this.models = [];
432      this._byId  = {};
433      this._byCid = {};
434    },
435
436    // Internal implementation of adding a single model to the set, updating
437    // hash indexes for `id` and `cid` lookups.
438    _add : function(model, options) {
439      options || (options = {});
440      if (!(model instanceof Backbone.Model)) {
441        model = new this.model(model);
442      }
443      var already = this.getByCid(model);
444      if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
445      this._byId[model.id] = model;
446      this._byCid[model.cid] = model;
447      model.collection = this;
448      var index = this.comparator ? this.sortedIndex(model, this.comparator) : this.length;
449      this.models.splice(index, 0, model);
450      model.bind('all', this._boundOnModelEvent);
451      this.length++;
452      if (!options.silent) this.trigger('add', model);
453      return model;
454    },
455
456    // Internal implementation of removing a single model from the set, updating
457    // hash indexes for `id` and `cid` lookups.
458    _remove : function(model, options) {
459      options || (options = {});
460      model = this.getByCid(model);
461      if (!model) return null;
462      delete this._byId[model.id];
463      delete this._byCid[model.cid];
464      delete model.collection;
465      this.models.splice(this.indexOf(model), 1);
466      model.unbind('all', this._boundOnModelEvent);
467      this.length--;
468      if (!options.silent) this.trigger('remove', model);
469      return model;
470    },
471
472    // Internal method called every time a model in the set fires an event.
473    // Sets need to update their indexes when models change ids.
474    _onModelEvent : function(ev, model, error) {
475      switch (ev) {
476        case 'change':
477          if (model.hasChanged('id')) {
478            delete this._byId[model.previous('id')];
479            this._byId[model.id] = model;
480          }
481          this.trigger('change', model);
482          break;
483        case 'error':
484          this.trigger('error', model, error);
485          break;
486      }
487    }
488
489  });
490
491  // Underscore methods that we want to implement on the Collection.
492  var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
493    'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
494    'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
495    'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'];
496
497  // Mix in each Underscore method as a proxy to `Collection#models`.
498  _.each(methods, function(method) {
499    Backbone.Collection.prototype[method] = function() {
500      return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
501    };
502  });
503
504  // Backbone.View
505  // -------------
506
507  // Creating a Backbone.View creates its initial element outside of the DOM,
508  // if an existing element is not provided...
509  Backbone.View = function(options) {
510    this._configure(options || {});
511    if (this.options.el) {
512      this.el = this.options.el;
513    } else {
514      var attrs = {};
515      if (this.id) attrs.id = this.id;
516      if (this.className) attrs.className = this.className;
517      this.el = this.make(this.tagName, attrs);
518    }
519    if (this.initialize) this.initialize(options);
520  };
521
522  // jQuery lookup, scoped to DOM elements within the current view.
523  // This should be prefered to global jQuery lookups, if you're dealing with
524  // a specific view.
525  var jQueryDelegate = function(selector) {
526    return $(selector, this.el);
527  };
528
529  // Cached regex to split keys for `handleEvents`.
530  var eventSplitter = /^(\w+)\s*(.*)$/;
531
532  // Set up all inheritable **Backbone.View** properties and methods.
533  _.extend(Backbone.View.prototype, {
534
535    // The default `tagName` of a View's element is `"div"`.
536    tagName : 'div',
537
538    // Attach the jQuery function as the `$` and `jQuery` properties.
539    $       : jQueryDelegate,
540    jQuery  : jQueryDelegate,
541
542    // **render** is the core function that your view should override, in order
543    // to populate its element (`this.el`), with the appropriate HTML. The
544    // convention is for **render** to always return `this`.
545    render : function() {
546      return this;
547    },
548
549    // For small amounts of DOM Elements, where a full-blown template isn't
550    // needed, use **make** to manufacture elements, one at a time.
551    //
552    //     var el = this.make('li', {'class': 'row'}, this.model.get('title'));
553    //
554    make : function(tagName, attributes, content) {
555      var el = document.createElement(tagName);
556      if (attributes) $(el).attr(attributes);
557      if (content) $(el).html(content);
558      return el;
559    },
560
561    // Set callbacks, where `this.callbacks` is a hash of
562    //
563    // *{"event selector": "callback"}*
564    //
565    //     {
566    //       'mousedown .title':  'edit',
567    //       'click .button':     'save'
568    //     }
569    //
570    // pairs. Callbacks will be bound to the view, with `this` set properly.
571    // Uses jQuery event delegation for efficiency.
572    // Omitting the selector binds the event to `this.el`.
573    // `"change"` events are not delegated through the view because IE does not
574    // bubble change events at all.
575    handleEvents : function(events) {
576      $(this.el).unbind();
577      if (!(events || (events = this.events))) return this;
578      for (var key in events) {
579        var methodName = events[key];
580        var match = key.match(eventSplitter);
581        var eventName = match[1], selector = match[2];
582        var method = _.bind(this[methodName], this);
583        if (selector === '' || eventName == 'change') {
584          $(this.el).bind(eventName, method);
585        } else {
586          $(this.el).delegate(selector, eventName, method);
587        }
588      }
589      return this;
590    },
591
592    // Performs the initial configuration of a View with a set of options.
593    // Keys with special meaning *(model, collection, id, className)*, are
594    // attached directly to the view.
595    _configure : function(options) {
596      if (this.options) options = _.extend({}, this.options, options);
597      if (options.model)      this.model      = options.model;
598      if (options.collection) this.collection = options.collection;
599      if (options.id)         this.id         = options.id;
600      if (options.className)  this.className  = options.className;
601      if (options.tagName)    this.tagName    = options.tagName;
602      this.options = options;
603    }
604
605  });
606
607  // Set up inheritance for the model, collection, and view.
608  var extend = Backbone.Model.extend = Backbone.Collection.extend = Backbone.View.extend = function (protoProps, classProps) {
609    var child = inherits(this, protoProps, classProps);
610    child.extend = extend;
611    return child;
612  };
613
614  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
615  var methodMap = {
616    'create': 'POST',
617    'update': 'PUT',
618    'delete': 'DELETE',
619    'read'  : 'GET'
620  };
621
622  // Backbone.sync
623  // -------------
624
625  // Override this function to change the manner in which Backbone persists
626  // models to the server. You will be passed the type of request, and the
627  // model in question. By default, uses jQuery to make a RESTful Ajax request
628  // to the model's `url()`. Some possible customizations could be:
629  //
630  // * Use `setTimeout` to batch rapid-fire updates into a single request.
631  // * Send up the models as XML instead of JSON.
632  // * Persist models via WebSockets instead of Ajax.
633  //
634  // Turn on `Backbone.emulateHttp` in order to send `PUT` and `DELETE` requests
635  // as `POST`, with an `_method` parameter containing the true HTTP method.
636  // Useful when interfacing with server-side languages like **PHP** that make
637  // it difficult to read the body of `PUT` requests.
638  Backbone.sync = function(method, model, success, error) {
639    var sendModel = method === 'create' || method === 'update';
640    var data = sendModel ? {model : JSON.stringify(model)} : {};
641    var type = methodMap[method];
642    if (Backbone.emulateHttp && (type === 'PUT' || type === 'DELETE')) {
643      data._method = type;
644      type = 'POST';
645    }
646    $.ajax({
647      url       : getUrl(model),
648      type      : type,
649      data      : data,
650      dataType  : 'json',
651      success   : success,
652      error     : error
653    });
654  };
655
656  // Helpers
657  // -------
658
659  // Helper function to correctly set up the prototype chain, for subclasses.
660  // Similar to `goog.inherits`, but uses a hash of prototype properties and
661  // class properties to be extended.
662  var inherits = function(parent, protoProps, classProps) {
663    var child;
664    if (protoProps.hasOwnProperty('constructor')) {
665      child = protoProps.constructor;
666    } else {
667      child = function(){ return parent.apply(this, arguments); };
668    }
669    var ctor = function(){};
670    ctor.prototype = parent.prototype;
671    child.prototype = new ctor();
672    _.extend(child.prototype, protoProps);
673    if (classProps) _.extend(child, classProps);
674    child.prototype.constructor = child;
675    return child;
676  };
677
678  // Helper function to get a URL from a Model or Collection as a property
679  // or as a function.
680  var getUrl = function(object) {
681    if (!(object && object.url)) throw new Error("A 'url' property or function must be specified");
682    return _.isFunction(object.url) ? object.url() : object.url;
683  };
684
685})();