PageRenderTime 6ms CodeModel.GetById 11ms app.highlight 30ms RepoModel.GetById 1ms app.codeStats 0ms

/backbone.js

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