PageRenderTime 3ms CodeModel.GetById 2ms app.highlight 41ms RepoModel.GetById 1ms app.codeStats 0ms

/Grails/backbone/web-app/js/lib/backbone.js

https://github.com/Refactr/open-source
JavaScript | 709 lines | 441 code | 85 blank | 183 comment | 122 complexity | 72ca466bce1b49364e1c96a0c61c2a66 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.2.0';
 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(model.parse(resp), 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(model.parse(resp), 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    // **parse** converts a response into the hash of attributes to be `set` on
251    // the model. The default implementation is just to pass the response along.
252    parse : function(resp) {
253      return resp;
254    },
255
256    // Create a new model with identical attributes to this one.
257    clone : function() {
258      return new this.constructor(this);
259    },
260
261    // A model is new if it has never been saved to the server, and has a negative
262    // ID.
263    isNew : function() {
264      return !this.id;
265    },
266
267    // Call this method to fire manually fire a `change` event for this model.
268    // Calling this will cause all objects observing the model to update.
269    change : function() {
270      this.trigger('change', this);
271      this._previousAttributes = _.clone(this.attributes);
272      this._changed = false;
273    },
274
275    // Determine if the model has changed since the last `"change"` event.
276    // If you specify an attribute name, determine if that attribute has changed.
277    hasChanged : function(attr) {
278      if (attr) return this._previousAttributes[attr] != this.attributes[attr];
279      return this._changed;
280    },
281
282    // Return an object containing all the attributes that have changed, or false
283    // if there are no changed attributes. Useful for determining what parts of a
284    // view need to be updated and/or what attributes need to be persisted to
285    // the server.
286    changedAttributes : function(now) {
287      now || (now = this.attributes);
288      var old = this._previousAttributes;
289      var changed = false;
290      for (var attr in now) {
291        if (!_.isEqual(old[attr], now[attr])) {
292          changed = changed || {};
293          changed[attr] = now[attr];
294        }
295      }
296      return changed;
297    },
298
299    // Get the previous value of an attribute, recorded at the time the last
300    // `"change"` event was fired.
301    previous : function(attr) {
302      if (!attr || !this._previousAttributes) return null;
303      return this._previousAttributes[attr];
304    },
305
306    // Get all of the attributes of the model at the time of the previous
307    // `"change"` event.
308    previousAttributes : function() {
309      return _.clone(this._previousAttributes);
310    }
311
312  });
313
314  // Backbone.Collection
315  // -------------------
316
317  // Provides a standard collection class for our sets of models, ordered
318  // or unordered. If a `comparator` is specified, the Collection will maintain
319  // its models in sort order, as they're added and removed.
320  Backbone.Collection = function(models, options) {
321    options || (options = {});
322    if (options.comparator) {
323      this.comparator = options.comparator;
324      delete options.comparator;
325    }
326    this._boundOnModelEvent = _.bind(this._onModelEvent, this);
327    this._reset();
328    if (models) this.refresh(models, {silent: true});
329    if (this.initialize) this.initialize(models, options);
330  };
331
332  // Define the Collection's inheritable methods.
333  _.extend(Backbone.Collection.prototype, Backbone.Events, {
334
335    // The default model for a collection is just a **Backbone.Model**.
336    // This should be overridden in most cases.
337    model : Backbone.Model,
338
339    // The JSON representation of a Collection is an array of the
340    // models' attributes.
341    toJSON : function() {
342      return this.map(function(model){ return model.toJSON(); });
343    },
344
345    // Add a model, or list of models to the set. Pass **silent** to avoid
346    // firing the `added` event for every new model.
347    add : function(models, options) {
348      if (_.isArray(models)) {
349        for (var i = 0, l = models.length; i < l; i++) {
350          this._add(models[i], options);
351        }
352      } else {
353        this._add(models, options);
354      }
355      return this;
356    },
357
358    // Remove a model, or a list of models from the set. Pass silent to avoid
359    // firing the `removed` event for every model removed.
360    remove : function(models, options) {
361      if (_.isArray(models)) {
362        for (var i = 0, l = models.length; i < l; i++) {
363          this._remove(models[i], options);
364        }
365      } else {
366        this._remove(models, options);
367      }
368      return this;
369    },
370
371    // Get a model from the set by id.
372    get : function(id) {
373      return id && this._byId[id.id != null ? id.id : id];
374    },
375
376    // Get a model from the set by client id.
377    getByCid : function(cid) {
378      return cid && this._byCid[cid.cid || cid];
379    },
380
381    // Get the model at the given index.
382    at: function(index) {
383      return this.models[index];
384    },
385
386    // Force the collection to re-sort itself. You don't need to call this under normal
387    // circumstances, as the set will maintain sort order as each item is added.
388    sort : function(options) {
389      options || (options = {});
390      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
391      this.models = this.sortBy(this.comparator);
392      if (!options.silent) this.trigger('refresh', this);
393      return this;
394    },
395
396    // Pluck an attribute from each model in the collection.
397    pluck : function(attr) {
398      return _.map(this.models, function(model){ return model.get(attr); });
399    },
400
401    // When you have more items than you want to add or remove individually,
402    // you can refresh the entire set with a new list of models, without firing
403    // any `added` or `removed` events. Fires `refresh` when finished.
404    refresh : function(models, options) {
405      models  || (models = []);
406      options || (options = {});
407      this._reset();
408      this.add(models, {silent: true});
409      if (!options.silent) this.trigger('refresh', this);
410      return this;
411    },
412
413    // Fetch the default set of models for this collection, refreshing the
414    // collection when they arrive.
415    fetch : function(options) {
416      options || (options = {});
417      var collection = this;
418      var success = function(resp) {
419        collection.refresh(collection.parse(resp));
420        if (options.success) options.success(collection, resp);
421      };
422      var error = options.error && _.bind(options.error, null, collection);
423      Backbone.sync('read', this, success, error);
424      return this;
425    },
426
427    // Create a new instance of a model in this collection. After the model
428    // has been created on the server, it will be added to the collection.
429    create : function(model, options) {
430      options || (options = {});
431      if (!(model instanceof Backbone.Model)) model = new this.model(model);
432      var coll = model.collection = this;
433      var success = function(nextModel, resp) {
434        coll.add(nextModel);
435        if (options.success) options.success(nextModel, resp);
436      };
437      return model.save(null, {success : success, error : options.error});
438    },
439
440    // **parse** converts a response into a list of models to be added to the
441    // collection. The default implementation is just to pass it through.
442    parse : function(resp) {
443      return resp;
444    },
445
446    // Proxy to _'s chain. Can't be proxied the same way the rest of the
447    // underscore methods are proxied because it relies on the underscore
448    // constructor.
449    chain: function () {
450      return _(this.models).chain();
451    },
452
453    // Reset all internal state. Called when the collection is refreshed.
454    _reset : function(options) {
455      this.length = 0;
456      this.models = [];
457      this._byId  = {};
458      this._byCid = {};
459    },
460
461    // Internal implementation of adding a single model to the set, updating
462    // hash indexes for `id` and `cid` lookups.
463    _add : function(model, options) {
464      options || (options = {});
465      if (!(model instanceof Backbone.Model)) {
466        model = new this.model(model);
467      }
468      var already = this.getByCid(model);
469      if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
470      this._byId[model.id] = model;
471      this._byCid[model.cid] = model;
472      model.collection = this;
473      var index = this.comparator ? this.sortedIndex(model, this.comparator) : this.length;
474      this.models.splice(index, 0, model);
475      model.bind('all', this._boundOnModelEvent);
476      this.length++;
477      if (!options.silent) this.trigger('add', model);
478      return model;
479    },
480
481    // Internal implementation of removing a single model from the set, updating
482    // hash indexes for `id` and `cid` lookups.
483    _remove : function(model, options) {
484      options || (options = {});
485      model = this.getByCid(model);
486      if (!model) return null;
487      delete this._byId[model.id];
488      delete this._byCid[model.cid];
489      delete model.collection;
490      this.models.splice(this.indexOf(model), 1);
491      model.unbind('all', this._boundOnModelEvent);
492      this.length--;
493      if (!options.silent) this.trigger('remove', model);
494      return model;
495    },
496
497    // Internal method called every time a model in the set fires an event.
498    // Sets need to update their indexes when models change ids. All other
499    // events simply proxy through.
500    _onModelEvent : function(ev, model) {
501      if (ev === 'change:id') {
502        delete this._byId[model.previous('id')];
503        this._byId[model.id] = model;
504      }
505      this.trigger.apply(this, arguments);
506    }
507
508  });
509
510  // Underscore methods that we want to implement on the Collection.
511  var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
512    'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
513    'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
514    'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'];
515
516  // Mix in each Underscore method as a proxy to `Collection#models`.
517  _.each(methods, function(method) {
518    Backbone.Collection.prototype[method] = function() {
519      return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
520    };
521  });
522
523  // Backbone.View
524  // -------------
525
526  // Creating a Backbone.View creates its initial element outside of the DOM,
527  // if an existing element is not provided...
528  Backbone.View = function(options) {
529    this._configure(options || {});
530    this._ensureElement();
531    this.delegateEvents();
532    if (this.initialize) this.initialize(options);
533  };
534
535  // jQuery lookup, scoped to DOM elements within the current view.
536  // This should be prefered to global jQuery lookups, if you're dealing with
537  // a specific view.
538  var jQueryDelegate = function(selector) {
539    return $(selector, this.el);
540  };
541
542  // Cached regex to split keys for `delegate`.
543  var eventSplitter = /^(\w+)\s*(.*)$/;
544
545  // Set up all inheritable **Backbone.View** properties and methods.
546  _.extend(Backbone.View.prototype, {
547
548    // The default `tagName` of a View's element is `"div"`.
549    tagName : 'div',
550
551    // Attach the jQuery function as the `$` and `jQuery` properties.
552    $       : jQueryDelegate,
553    jQuery  : jQueryDelegate,
554
555    // **render** is the core function that your view should override, in order
556    // to populate its element (`this.el`), with the appropriate HTML. The
557    // convention is for **render** to always return `this`.
558    render : function() {
559      return this;
560    },
561
562    // For small amounts of DOM Elements, where a full-blown template isn't
563    // needed, use **make** to manufacture elements, one at a time.
564    //
565    //     var el = this.make('li', {'class': 'row'}, this.model.get('title'));
566    //
567    make : function(tagName, attributes, content) {
568      var el = document.createElement(tagName);
569      if (attributes) $(el).attr(attributes);
570      if (content) $(el).html(content);
571      return el;
572    },
573
574    // Set callbacks, where `this.callbacks` is a hash of
575    //
576    // *{"event selector": "callback"}*
577    //
578    //     {
579    //       'mousedown .title':  'edit',
580    //       'click .button':     'save'
581    //     }
582    //
583    // pairs. Callbacks will be bound to the view, with `this` set properly.
584    // Uses jQuery event delegation for efficiency.
585    // Omitting the selector binds the event to `this.el`.
586    // This only works for delegate-able events: not `focus`, `blur`, and
587    // not `change`, `submit`, and `reset` in Internet Explorer.
588    delegateEvents : function(events) {
589      if (!(events || (events = this.events))) return this;
590      $(this.el).unbind();
591      for (var key in events) {
592        var methodName = events[key];
593        var match = key.match(eventSplitter);
594        var eventName = match[1], selector = match[2];
595        var method = _.bind(this[methodName], this);
596        if (selector === '') {
597          $(this.el).bind(eventName, method);
598        } else {
599          $(this.el).delegate(selector, eventName, method);
600        }
601      }
602      return this;
603    },
604
605    // Performs the initial configuration of a View with a set of options.
606    // Keys with special meaning *(model, collection, id, className)*, are
607    // attached directly to the view.
608    _configure : function(options) {
609      if (this.options) options = _.extend({}, this.options, options);
610      if (options.model)      this.model      = options.model;
611      if (options.collection) this.collection = options.collection;
612      if (options.el)         this.el         = options.el;
613      if (options.id)         this.id         = options.id;
614      if (options.className)  this.className  = options.className;
615      if (options.tagName)    this.tagName    = options.tagName;
616      this.options = options;
617    },
618
619    // Ensure that the View has a DOM element to render into.
620    _ensureElement : function() {
621      if (this.el) return;
622      var attrs = {};
623      if (this.id) attrs.id = this.id;
624      if (this.className) attrs.className = this.className;
625      this.el = this.make(this.tagName, attrs);
626    }
627
628  });
629
630  // Set up inheritance for the model, collection, and view.
631  var extend = Backbone.Model.extend = Backbone.Collection.extend = Backbone.View.extend = function (protoProps, classProps) {
632    var child = inherits(this, protoProps, classProps);
633    child.extend = extend;
634    return child;
635  };
636
637  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
638  var methodMap = {
639    'create': 'POST',
640    'update': 'PUT',
641    'delete': 'DELETE',
642    'read'  : 'GET'
643  };
644
645  // Backbone.sync
646  // -------------
647
648  // Override this function to change the manner in which Backbone persists
649  // models to the server. You will be passed the type of request, and the
650  // model in question. By default, uses jQuery to make a RESTful Ajax request
651  // to the model's `url()`. Some possible customizations could be:
652  //
653  // * Use `setTimeout` to batch rapid-fire updates into a single request.
654  // * Send up the models as XML instead of JSON.
655  // * Persist models via WebSockets instead of Ajax.
656  //
657  // Turn on `Backbone.emulateHttp` in order to send `PUT` and `DELETE` requests
658  // as `POST`, with an `_method` parameter containing the true HTTP method.
659  // Useful when interfacing with server-side languages like **PHP** that make
660  // it difficult to read the body of `PUT` requests.
661  Backbone.sync = function(method, model, success, error) {
662    var sendModel = method === 'create' || method === 'update';
663    var data = sendModel ? {model : JSON.stringify(model)} : {};
664    var type = methodMap[method];
665    if (Backbone.emulateHttp && (type === 'PUT' || type === 'DELETE')) {
666      data._method = type;
667      type = 'POST';
668    }
669    $.ajax({
670      url       : getUrl(model),
671      type      : type,
672      data      : data,
673      dataType  : 'json',
674      success   : success,
675      error     : error
676    });
677  };
678
679  // Helpers
680  // -------
681
682  // Helper function to correctly set up the prototype chain, for subclasses.
683  // Similar to `goog.inherits`, but uses a hash of prototype properties and
684  // class properties to be extended.
685  var inherits = function(parent, protoProps, classProps) {
686    var child;
687    if (protoProps.hasOwnProperty('constructor')) {
688      child = protoProps.constructor;
689    } else {
690      child = function(){ return parent.apply(this, arguments); };
691    }
692    var ctor = function(){};
693    ctor.prototype = parent.prototype;
694    child.prototype = new ctor();
695    _.extend(child.prototype, protoProps);
696    if (classProps) _.extend(child, classProps);
697    child.prototype.constructor = child;
698    child.__super__ = parent.prototype;
699    return child;
700  };
701
702  // Helper function to get a URL from a Model or Collection as a property
703  // or as a function.
704  var getUrl = function(object) {
705    if (!(object && object.url)) throw new Error("A 'url' property or function must be specified");
706    return _.isFunction(object.url) ? object.url() : object.url;
707  };
708
709})();