rails-backbone 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/README.md +40 -0
  3. data/Rakefile +48 -0
  4. data/lib/backbone-rails.rb +12 -0
  5. data/lib/generators/backbone/controller/controller_generator.rb +47 -0
  6. data/lib/generators/backbone/controller/templates/controller.coffee +14 -0
  7. data/lib/generators/backbone/controller/templates/template.jst +2 -0
  8. data/lib/generators/backbone/controller/templates/view.coffee +8 -0
  9. data/lib/generators/backbone/install/install_generator.rb +39 -0
  10. data/lib/generators/backbone/install/templates/app.coffee +11 -0
  11. data/lib/generators/backbone/model/model_generator.rb +19 -0
  12. data/lib/generators/backbone/model/templates/model.coffee +11 -0
  13. data/lib/generators/backbone/resource_helpers.rb +31 -0
  14. data/lib/generators/backbone/scaffold/scaffold_generator.rb +31 -0
  15. data/lib/generators/backbone/scaffold/templates/controller.coffee +32 -0
  16. data/lib/generators/backbone/scaffold/templates/model.coffee +11 -0
  17. data/lib/generators/backbone/scaffold/templates/templates/edit.jst +17 -0
  18. data/lib/generators/backbone/scaffold/templates/templates/index.jst +16 -0
  19. data/lib/generators/backbone/scaffold/templates/templates/model.jst +7 -0
  20. data/lib/generators/backbone/scaffold/templates/templates/new.jst +17 -0
  21. data/lib/generators/backbone/scaffold/templates/templates/show.jst +9 -0
  22. data/lib/generators/backbone/scaffold/templates/views/edit_view.coffee +24 -0
  23. data/lib/generators/backbone/scaffold/templates/views/index_view.coffee +22 -0
  24. data/lib/generators/backbone/scaffold/templates/views/model_view.coffee +19 -0
  25. data/lib/generators/backbone/scaffold/templates/views/new_view.coffee +25 -0
  26. data/lib/generators/backbone/scaffold/templates/views/show_view.coffee +8 -0
  27. data/lib/tasks/backbone-rails_tasks.rake +4 -0
  28. data/vendor/assets/javascripts/backbone.js +1098 -0
  29. data/vendor/assets/javascripts/backbone_datalink.js +21 -0
  30. data/vendor/assets/javascripts/backbone_rails_sync.js +51 -0
  31. data/vendor/assets/javascripts/underscore.js +818 -0
  32. metadata +126 -0
@@ -0,0 +1,17 @@
1
+ <h1>New <%= singular_table_name %></h1>
2
+
3
+ <form id="new-<%= singular_table_name %>" name="<%= singular_table_name %>">
4
+ <% attributes.each do |attribute| -%>
5
+ <div class="field">
6
+ <label for="<%= attribute.name %>"> <%= attribute.name %>:</label>
7
+ <input type="text" name="<%= attribute.name %>" id="<%= attribute.name %>" value=<%%= <%= attribute.name %> %> >
8
+ </div>
9
+
10
+ <% end -%>
11
+ <div class="actions">
12
+ <input type="submit" value="Create <%= human_name %>" />
13
+ </div>
14
+
15
+ </form>
16
+
17
+ <a href="#/index">Back</a>
@@ -0,0 +1,9 @@
1
+ <% attributes.each do |attribute| -%>
2
+ <p>
3
+ <b><%= attribute.human_name %>:</b>
4
+ <%%= <%= attribute.name %> %>
5
+ </p>
6
+
7
+ <% end -%>
8
+
9
+ <a href="#/index">Back</a>
@@ -0,0 +1,24 @@
1
+ <%= view_namespace %> ||= {}
2
+
3
+ class <%= view_namespace %>.EditView extends Backbone.View
4
+ template: JST["<%= jst 'edit' %>"]
5
+
6
+ events:
7
+ "submit #edit-<%= singular_name %>": "update"
8
+
9
+ update: (e) ->
10
+ e.preventDefault()
11
+ e.stopPropagation()
12
+
13
+ @options.model.save(null,
14
+ success:(model) =>
15
+ @options.model = model
16
+ window.location.hash = "/#{@options.model.id}"
17
+ )
18
+
19
+ render: ->
20
+ $(this.el).html(this.template(@options.model.toJSON() ))
21
+
22
+ this.$("form").backboneLink(@options.model)
23
+
24
+ return this
@@ -0,0 +1,22 @@
1
+ <%= view_namespace %> ||= {}
2
+
3
+ class <%= view_namespace %>.IndexView extends Backbone.View
4
+ template: JST["<%= jst 'index' %>"]
5
+
6
+ initialize: () ->
7
+ _.bindAll(this, 'addOne', 'addAll', 'render');
8
+
9
+ @options.<%= plural_name %>.bind('refresh', this.addAll);
10
+
11
+ addAll: () ->
12
+ @options.<%= plural_name %>.each(this.addOne)
13
+
14
+ addOne: (<%= singular_name %>) ->
15
+ view = new <%= view_namespace %>.<%= singular_name.capitalize %>View({model : <%= singular_name %>})
16
+ this.$("tbody").append(view.render().el)
17
+
18
+ render: ->
19
+ $(this.el).html(this.template(<%= plural_name %>: this.options.<%= plural_name %>.toJSON() ))
20
+ @addAll()
21
+
22
+ return this
@@ -0,0 +1,19 @@
1
+ <%= view_namespace %> ||= {}
2
+
3
+ class <%= view_namespace %>.<%= singular_name.capitalize %>View extends Backbone.View
4
+ template: JST["<%= jst singular_name %>"]
5
+
6
+ events:
7
+ "click .destroy" : "destroy"
8
+
9
+ tagName: "tr"
10
+
11
+ destroy: () ->
12
+ @options.model.destroy()
13
+ this.remove()
14
+
15
+ return false
16
+
17
+ render: ->
18
+ $(this.el).html(this.template(this.options.model.toJSON() ))
19
+ return this
@@ -0,0 +1,25 @@
1
+ <%= view_namespace %> ||= {}
2
+
3
+ class <%= view_namespace %>.NewView extends Backbone.View
4
+ template: JST["<%= jst 'new' %>"]
5
+
6
+ events:
7
+ "submit #new-<%= singular_name %>": "save"
8
+
9
+ save: (e) ->
10
+ e.preventDefault()
11
+ e.stopPropagation()
12
+
13
+ @options.collection.create(@options.model.toJSON(),
14
+ success: (model) =>
15
+ @options.model = model
16
+ window.location.hash = "/#{@options.model.id}"
17
+ )
18
+
19
+ render: ->
20
+ @options.model = new @options.collection.model()
21
+ $(this.el).html(this.template(@options.model.toJSON() ))
22
+
23
+ this.$("form").backboneLink(@options.model)
24
+
25
+ return this
@@ -0,0 +1,8 @@
1
+ <%= view_namespace %> ||= {}
2
+
3
+ class <%= view_namespace %>.ShowView extends Backbone.View
4
+ template: JST["<%= jst 'show' %>"]
5
+
6
+ render: ->
7
+ $(this.el).html(this.template(this.options.model.toJSON() ))
8
+ return this
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :backbone-rails do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,1098 @@
1
+ // Backbone.js 0.3.3
2
+ // (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
3
+ // Backbone may be freely distributed under the MIT license.
4
+ // For all details and documentation:
5
+ // http://documentcloud.github.com/backbone
6
+
7
+ (function(){
8
+
9
+ // Initial Setup
10
+ // -------------
11
+
12
+ // Save a reference to the global object.
13
+ var root = this;
14
+
15
+ // Save the previous value of the `Backbone` variable.
16
+ var previousBackbone = root.Backbone;
17
+
18
+ // The top-level namespace. All public Backbone classes and modules will
19
+ // be attached to this. Exported for both CommonJS and the browser.
20
+ var Backbone;
21
+ if (typeof exports !== 'undefined') {
22
+ Backbone = exports;
23
+ } else {
24
+ Backbone = root.Backbone = {};
25
+ }
26
+
27
+ // Current version of the library. Keep in sync with `package.json`.
28
+ Backbone.VERSION = '0.3.3';
29
+
30
+ // Require Underscore, if we're on the server, and it's not already present.
31
+ var _ = root._;
32
+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore')._;
33
+
34
+ // For Backbone's purposes, jQuery or Zepto owns the `$` variable.
35
+ var $ = root.jQuery || root.Zepto;
36
+
37
+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
38
+ // to its previous owner. Returns a reference to this Backbone object.
39
+ Backbone.noConflict = function() {
40
+ root.Backbone = previousBackbone;
41
+ return this;
42
+ };
43
+
44
+ // Turn on `emulateHTTP` to use support legacy HTTP servers. Setting this option will
45
+ // fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and set a
46
+ // `X-Http-Method-Override` header.
47
+ Backbone.emulateHTTP = false;
48
+
49
+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
50
+ // `application/json` requests ... will encode the body as
51
+ // `application/x-www-form-urlencoded` instead and will send the model in a
52
+ // form param named `model`.
53
+ Backbone.emulateJSON = false;
54
+
55
+ // Backbone.Events
56
+ // -----------------
57
+
58
+ // A module that can be mixed in to *any object* in order to provide it with
59
+ // custom events. You may `bind` or `unbind` a callback function to an event;
60
+ // `trigger`-ing an event fires all callbacks in succession.
61
+ //
62
+ // var object = {};
63
+ // _.extend(object, Backbone.Events);
64
+ // object.bind('expand', function(){ alert('expanded'); });
65
+ // object.trigger('expand');
66
+ //
67
+ Backbone.Events = {
68
+
69
+ // Bind an event, specified by a string name, `ev`, to a `callback` function.
70
+ // Passing `"all"` will bind the callback to all events fired.
71
+ bind : function(ev, callback) {
72
+ var calls = this._callbacks || (this._callbacks = {});
73
+ var list = this._callbacks[ev] || (this._callbacks[ev] = []);
74
+ list.push(callback);
75
+ return this;
76
+ },
77
+
78
+ // Remove one or many callbacks. If `callback` is null, removes all
79
+ // callbacks for the event. If `ev` is null, removes all bound callbacks
80
+ // for all events.
81
+ unbind : function(ev, callback) {
82
+ var calls;
83
+ if (!ev) {
84
+ this._callbacks = {};
85
+ } else if (calls = this._callbacks) {
86
+ if (!callback) {
87
+ calls[ev] = [];
88
+ } else {
89
+ var list = calls[ev];
90
+ if (!list) return this;
91
+ for (var i = 0, l = list.length; i < l; i++) {
92
+ if (callback === list[i]) {
93
+ list[i] = null;
94
+ break;
95
+ }
96
+ }
97
+ }
98
+ }
99
+ return this;
100
+ },
101
+
102
+ // Trigger an event, firing all bound callbacks. Callbacks are passed the
103
+ // same arguments as `trigger` is, apart from the event name.
104
+ // Listening for `"all"` passes the true event name as the first argument.
105
+ trigger : function(eventName) {
106
+ var list, calls, ev, callback, args, i, l;
107
+ var both = 2;
108
+ if (!(calls = this._callbacks)) return this;
109
+ while (both--) {
110
+ ev = both ? eventName : 'all';
111
+ if (list = calls[ev]) {
112
+ for (i = 0, l = list.length; i < l; i++) {
113
+ if (!(callback = list[i])) {
114
+ list.splice(i, 1); i--; l--;
115
+ } else {
116
+ args = both ? Array.prototype.slice.call(arguments, 1) : arguments;
117
+ callback.apply(this, args);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ return this;
123
+ }
124
+
125
+ };
126
+
127
+ // Backbone.Model
128
+ // --------------
129
+
130
+ // Create a new model, with defined attributes. A client id (`cid`)
131
+ // is automatically generated and assigned for you.
132
+ Backbone.Model = function(attributes, options) {
133
+ var defaults;
134
+ attributes || (attributes = {});
135
+ if (defaults = this.defaults) {
136
+ if (_.isFunction(defaults)) defaults = defaults();
137
+ attributes = _.extend({}, defaults, attributes);
138
+ }
139
+ this.attributes = {};
140
+ this._escapedAttributes = {};
141
+ this.cid = _.uniqueId('c');
142
+ this.set(attributes, {silent : true});
143
+ this._changed = false;
144
+ this._previousAttributes = _.clone(this.attributes);
145
+ if (options && options.collection) this.collection = options.collection;
146
+ this.initialize(attributes, options);
147
+ };
148
+
149
+ // Attach all inheritable methods to the Model prototype.
150
+ _.extend(Backbone.Model.prototype, Backbone.Events, {
151
+
152
+ // A snapshot of the model's previous attributes, taken immediately
153
+ // after the last `"change"` event was fired.
154
+ _previousAttributes : null,
155
+
156
+ // Has the item been changed since the last `"change"` event?
157
+ _changed : false,
158
+
159
+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
160
+ // CouchDB users may want to set this to `"_id"`.
161
+ idAttribute : 'id',
162
+
163
+ // Initialize is an empty function by default. Override it with your own
164
+ // initialization logic.
165
+ initialize : function(){},
166
+
167
+ // Return a copy of the model's `attributes` object.
168
+ toJSON : function() {
169
+ return _.clone(this.attributes);
170
+ },
171
+
172
+ // Get the value of an attribute.
173
+ get : function(attr) {
174
+ return this.attributes[attr];
175
+ },
176
+
177
+ // Get the HTML-escaped value of an attribute.
178
+ escape : function(attr) {
179
+ var html;
180
+ if (html = this._escapedAttributes[attr]) return html;
181
+ var val = this.attributes[attr];
182
+ return this._escapedAttributes[attr] = escapeHTML(val == null ? '' : '' + val);
183
+ },
184
+
185
+ // Returns `true` if the attribute contains a value that is not null
186
+ // or undefined.
187
+ has : function(attr) {
188
+ return this.attributes[attr] != null;
189
+ },
190
+
191
+ // Set a hash of model attributes on the object, firing `"change"` unless you
192
+ // choose to silence it.
193
+ set : function(attrs, options) {
194
+
195
+ // Extract attributes and options.
196
+ options || (options = {});
197
+ if (!attrs) return this;
198
+ if (attrs.attributes) attrs = attrs.attributes;
199
+ var now = this.attributes, escaped = this._escapedAttributes;
200
+
201
+ // Run validation.
202
+ if (!options.silent && this.validate && !this._performValidation(attrs, options)) return false;
203
+
204
+ // Check for changes of `id`.
205
+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
206
+
207
+ // Update attributes.
208
+ for (var attr in attrs) {
209
+ var val = attrs[attr];
210
+ if (!_.isEqual(now[attr], val)) {
211
+ now[attr] = val;
212
+ delete escaped[attr];
213
+ this._changed = true;
214
+ if (!options.silent) this.trigger('change:' + attr, this, val, options);
215
+ }
216
+ }
217
+
218
+ // Fire the `"change"` event, if the model has been changed.
219
+ if (!options.silent && this._changed) this.change(options);
220
+ return this;
221
+ },
222
+
223
+ // Remove an attribute from the model, firing `"change"` unless you choose
224
+ // to silence it. `unset` is a noop if the attribute doesn't exist.
225
+ unset : function(attr, options) {
226
+ if (!(attr in this.attributes)) return this;
227
+ options || (options = {});
228
+ var value = this.attributes[attr];
229
+
230
+ // Run validation.
231
+ var validObj = {};
232
+ validObj[attr] = void 0;
233
+ if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
234
+
235
+ // Remove the attribute.
236
+ delete this.attributes[attr];
237
+ delete this._escapedAttributes[attr];
238
+ if (attr == this.idAttribute) delete this.id;
239
+ this._changed = true;
240
+ if (!options.silent) {
241
+ this.trigger('change:' + attr, this, void 0, options);
242
+ this.change(options);
243
+ }
244
+ return this;
245
+ },
246
+
247
+ // Clear all attributes on the model, firing `"change"` unless you choose
248
+ // to silence it.
249
+ clear : function(options) {
250
+ options || (options = {});
251
+ var old = this.attributes;
252
+
253
+ // Run validation.
254
+ var validObj = {};
255
+ for (attr in old) validObj[attr] = void 0;
256
+ if (!options.silent && this.validate && !this._performValidation(validObj, options)) return false;
257
+
258
+ this.attributes = {};
259
+ this._escapedAttributes = {};
260
+ this._changed = true;
261
+ if (!options.silent) {
262
+ for (attr in old) {
263
+ this.trigger('change:' + attr, this, void 0, options);
264
+ }
265
+ this.change(options);
266
+ }
267
+ return this;
268
+ },
269
+
270
+ // Fetch the model from the server. If the server's representation of the
271
+ // model differs from its current attributes, they will be overriden,
272
+ // triggering a `"change"` event.
273
+ fetch : function(options) {
274
+ options || (options = {});
275
+ var model = this;
276
+ var success = options.success;
277
+ options.success = function(resp, status, xhr) {
278
+ if (!model.set(model.parse(resp, xhr), options)) return false;
279
+ if (success) success(model, resp);
280
+ };
281
+ options.error = wrapError(options.error, model, options);
282
+ return (this.sync || Backbone.sync).call(this, 'read', this, options);
283
+ },
284
+
285
+ // Set a hash of model attributes, and sync the model to the server.
286
+ // If the server returns an attributes hash that differs, the model's
287
+ // state will be `set` again.
288
+ save : function(attrs, options) {
289
+ options || (options = {});
290
+ if (attrs && !this.set(attrs, options)) return false;
291
+ var model = this;
292
+ var success = options.success;
293
+ options.success = function(resp, status, xhr) {
294
+ if (!model.set(model.parse(resp, xhr), options)) return false;
295
+ if (success) success(model, resp, xhr);
296
+ };
297
+ options.error = wrapError(options.error, model, options);
298
+ var method = this.isNew() ? 'create' : 'update';
299
+ return (this.sync || Backbone.sync).call(this, method, this, options);
300
+ },
301
+
302
+ // Destroy this model on the server. Upon success, the model is removed
303
+ // from its collection, if it has one.
304
+ destroy : function(options) {
305
+ options || (options = {});
306
+ var model = this;
307
+ var success = options.success;
308
+ options.success = function(resp) {
309
+ model.trigger('destroy', model, model.collection, options);
310
+ if (success) success(model, resp);
311
+ };
312
+ options.error = wrapError(options.error, model, options);
313
+ return (this.sync || Backbone.sync).call(this, 'delete', this, options);
314
+ },
315
+
316
+ // Default URL for the model's representation on the server -- if you're
317
+ // using Backbone's restful methods, override this to change the endpoint
318
+ // that will be called.
319
+ url : function() {
320
+ var base = getUrl(this.collection) || this.urlRoot || urlError();
321
+ if (this.isNew()) return base;
322
+ return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
323
+ },
324
+
325
+ // **parse** converts a response into the hash of attributes to be `set` on
326
+ // the model. The default implementation is just to pass the response along.
327
+ parse : function(resp, xhr) {
328
+ return resp;
329
+ },
330
+
331
+ // Create a new model with identical attributes to this one.
332
+ clone : function() {
333
+ return new this.constructor(this);
334
+ },
335
+
336
+ // A model is new if it has never been saved to the server, and has a negative
337
+ // ID.
338
+ isNew : function() {
339
+ return !this.id;
340
+ },
341
+
342
+ // Call this method to manually fire a `change` event for this model.
343
+ // Calling this will cause all objects observing the model to update.
344
+ change : function(options) {
345
+ this.trigger('change', this, options);
346
+ this._previousAttributes = _.clone(this.attributes);
347
+ this._changed = false;
348
+ },
349
+
350
+ // Determine if the model has changed since the last `"change"` event.
351
+ // If you specify an attribute name, determine if that attribute has changed.
352
+ hasChanged : function(attr) {
353
+ if (attr) return this._previousAttributes[attr] != this.attributes[attr];
354
+ return this._changed;
355
+ },
356
+
357
+ // Return an object containing all the attributes that have changed, or false
358
+ // if there are no changed attributes. Useful for determining what parts of a
359
+ // view need to be updated and/or what attributes need to be persisted to
360
+ // the server.
361
+ changedAttributes : function(now) {
362
+ now || (now = this.attributes);
363
+ var old = this._previousAttributes;
364
+ var changed = false;
365
+ for (var attr in now) {
366
+ if (!_.isEqual(old[attr], now[attr])) {
367
+ changed = changed || {};
368
+ changed[attr] = now[attr];
369
+ }
370
+ }
371
+ return changed;
372
+ },
373
+
374
+ // Get the previous value of an attribute, recorded at the time the last
375
+ // `"change"` event was fired.
376
+ previous : function(attr) {
377
+ if (!attr || !this._previousAttributes) return null;
378
+ return this._previousAttributes[attr];
379
+ },
380
+
381
+ // Get all of the attributes of the model at the time of the previous
382
+ // `"change"` event.
383
+ previousAttributes : function() {
384
+ return _.clone(this._previousAttributes);
385
+ },
386
+
387
+ // Run validation against a set of incoming attributes, returning `true`
388
+ // if all is well. If a specific `error` callback has been passed,
389
+ // call that instead of firing the general `"error"` event.
390
+ _performValidation : function(attrs, options) {
391
+ var error = this.validate(attrs);
392
+ if (error) {
393
+ if (options.error) {
394
+ options.error(this, error);
395
+ } else {
396
+ this.trigger('error', this, error, options);
397
+ }
398
+ return false;
399
+ }
400
+ return true;
401
+ }
402
+
403
+ });
404
+
405
+ // Backbone.Collection
406
+ // -------------------
407
+
408
+ // Provides a standard collection class for our sets of models, ordered
409
+ // or unordered. If a `comparator` is specified, the Collection will maintain
410
+ // its models in sort order, as they're added and removed.
411
+ Backbone.Collection = function(models, options) {
412
+ options || (options = {});
413
+ if (options.comparator) {
414
+ this.comparator = options.comparator;
415
+ delete options.comparator;
416
+ }
417
+ _.bindAll(this, '_onModelEvent', '_removeReference');
418
+ this._reset();
419
+ if (models) this.refresh(models, {silent: true});
420
+ this.initialize(models, options);
421
+ };
422
+
423
+ // Define the Collection's inheritable methods.
424
+ _.extend(Backbone.Collection.prototype, Backbone.Events, {
425
+
426
+ // The default model for a collection is just a **Backbone.Model**.
427
+ // This should be overridden in most cases.
428
+ model : Backbone.Model,
429
+
430
+ // Initialize is an empty function by default. Override it with your own
431
+ // initialization logic.
432
+ initialize : function(){},
433
+
434
+ // The JSON representation of a Collection is an array of the
435
+ // models' attributes.
436
+ toJSON : function() {
437
+ return this.map(function(model){ return model.toJSON(); });
438
+ },
439
+
440
+ // Add a model, or list of models to the set. Pass **silent** to avoid
441
+ // firing the `added` event for every new model.
442
+ add : function(models, options) {
443
+ if (_.isArray(models)) {
444
+ for (var i = 0, l = models.length; i < l; i++) {
445
+ this._add(models[i], options);
446
+ }
447
+ } else {
448
+ this._add(models, options);
449
+ }
450
+ return this;
451
+ },
452
+
453
+ // Remove a model, or a list of models from the set. Pass silent to avoid
454
+ // firing the `removed` event for every model removed.
455
+ remove : function(models, options) {
456
+ if (_.isArray(models)) {
457
+ for (var i = 0, l = models.length; i < l; i++) {
458
+ this._remove(models[i], options);
459
+ }
460
+ } else {
461
+ this._remove(models, options);
462
+ }
463
+ return this;
464
+ },
465
+
466
+ // Get a model from the set by id.
467
+ get : function(id) {
468
+ if (id == null) return null;
469
+ return this._byId[id.id != null ? id.id : id];
470
+ },
471
+
472
+ // Get a model from the set by client id.
473
+ getByCid : function(cid) {
474
+ return cid && this._byCid[cid.cid || cid];
475
+ },
476
+
477
+ // Get the model at the given index.
478
+ at: function(index) {
479
+ return this.models[index];
480
+ },
481
+
482
+ // Force the collection to re-sort itself. You don't need to call this under normal
483
+ // circumstances, as the set will maintain sort order as each item is added.
484
+ sort : function(options) {
485
+ options || (options = {});
486
+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
487
+ this.models = this.sortBy(this.comparator);
488
+ if (!options.silent) this.trigger('refresh', this, options);
489
+ return this;
490
+ },
491
+
492
+ // Pluck an attribute from each model in the collection.
493
+ pluck : function(attr) {
494
+ return _.map(this.models, function(model){ return model.get(attr); });
495
+ },
496
+
497
+ // When you have more items than you want to add or remove individually,
498
+ // you can refresh the entire set with a new list of models, without firing
499
+ // any `added` or `removed` events. Fires `refresh` when finished.
500
+ refresh : function(models, options) {
501
+ models || (models = []);
502
+ options || (options = {});
503
+ this.each(this._removeReference);
504
+ this._reset();
505
+ this.add(models, {silent: true});
506
+ if (!options.silent) this.trigger('refresh', this, options);
507
+ return this;
508
+ },
509
+
510
+ // Fetch the default set of models for this collection, refreshing the
511
+ // collection when they arrive. If `add: true` is passed, appends the
512
+ // models to the collection instead of refreshing.
513
+ fetch : function(options) {
514
+ options || (options = {});
515
+ var collection = this;
516
+ var success = options.success;
517
+ options.success = function(resp, status, xhr) {
518
+ collection[options.add ? 'add' : 'refresh'](collection.parse(resp, xhr), options);
519
+ if (success) success(collection, resp);
520
+ };
521
+ options.error = wrapError(options.error, collection, options);
522
+ return (this.sync || Backbone.sync).call(this, 'read', this, options);
523
+ },
524
+
525
+ // Create a new instance of a model in this collection. After the model
526
+ // has been created on the server, it will be added to the collection.
527
+ create : function(model, options) {
528
+ var coll = this;
529
+ options || (options = {});
530
+ if (!(model instanceof Backbone.Model)) {
531
+ var attrs = model;
532
+ model = new this.model(null, {collection: coll});
533
+ if (!model.set(attrs, options)) return false;
534
+ } else {
535
+ model.collection = coll;
536
+ }
537
+ var success = options.success;
538
+ options.success = function(nextModel, resp, xhr) {
539
+ coll.add(nextModel);
540
+ if (success) success(nextModel, resp, xhr);
541
+ };
542
+ model.save(null, options);
543
+ return model;
544
+ },
545
+
546
+ // **parse** converts a response into a list of models to be added to the
547
+ // collection. The default implementation is just to pass it through.
548
+ parse : function(resp, xhr) {
549
+ return resp;
550
+ },
551
+
552
+ // Proxy to _'s chain. Can't be proxied the same way the rest of the
553
+ // underscore methods are proxied because it relies on the underscore
554
+ // constructor.
555
+ chain: function () {
556
+ return _(this.models).chain();
557
+ },
558
+
559
+ // Reset all internal state. Called when the collection is refreshed.
560
+ _reset : function(options) {
561
+ this.length = 0;
562
+ this.models = [];
563
+ this._byId = {};
564
+ this._byCid = {};
565
+ },
566
+
567
+ // Internal implementation of adding a single model to the set, updating
568
+ // hash indexes for `id` and `cid` lookups.
569
+ _add : function(model, options) {
570
+ options || (options = {});
571
+ if (!(model instanceof Backbone.Model)) {
572
+ model = new this.model(model, {collection: this});
573
+ }
574
+ var already = this.getByCid(model);
575
+ if (already) throw new Error(["Can't add the same model to a set twice", already.id]);
576
+ this._byId[model.id] = model;
577
+ this._byCid[model.cid] = model;
578
+ if (!model.collection) {
579
+ model.collection = this;
580
+ }
581
+ var index = this.comparator ? this.sortedIndex(model, this.comparator) : this.length;
582
+ this.models.splice(index, 0, model);
583
+ model.bind('all', this._onModelEvent);
584
+ this.length++;
585
+ if (!options.silent) model.trigger('add', model, this, options);
586
+ return model;
587
+ },
588
+
589
+ // Internal implementation of removing a single model from the set, updating
590
+ // hash indexes for `id` and `cid` lookups.
591
+ _remove : function(model, options) {
592
+ options || (options = {});
593
+ model = this.getByCid(model) || this.get(model);
594
+ if (!model) return null;
595
+ delete this._byId[model.id];
596
+ delete this._byCid[model.cid];
597
+ this.models.splice(this.indexOf(model), 1);
598
+ this.length--;
599
+ if (!options.silent) model.trigger('remove', model, this, options);
600
+ this._removeReference(model);
601
+ return model;
602
+ },
603
+
604
+ // Internal method to remove a model's ties to a collection.
605
+ _removeReference : function(model) {
606
+ if (this == model.collection) {
607
+ delete model.collection;
608
+ }
609
+ model.unbind('all', this._onModelEvent);
610
+ },
611
+
612
+ // Internal method called every time a model in the set fires an event.
613
+ // Sets need to update their indexes when models change ids. All other
614
+ // events simply proxy through. "add" and "remove" events that originate
615
+ // in other collections are ignored.
616
+ _onModelEvent : function(ev, model, collection, options) {
617
+ if ((ev == 'add' || ev == 'remove') && collection != this) return;
618
+ if (ev == 'destroy') {
619
+ this._remove(model, options);
620
+ }
621
+ if (model && ev === 'change:' + model.idAttribute) {
622
+ delete this._byId[model.previous(model.idAttribute)];
623
+ this._byId[model.id] = model;
624
+ }
625
+ this.trigger.apply(this, arguments);
626
+ }
627
+
628
+ });
629
+
630
+ // Underscore methods that we want to implement on the Collection.
631
+ var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect',
632
+ 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
633
+ 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size',
634
+ 'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty'];
635
+
636
+ // Mix in each Underscore method as a proxy to `Collection#models`.
637
+ _.each(methods, function(method) {
638
+ Backbone.Collection.prototype[method] = function() {
639
+ return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
640
+ };
641
+ });
642
+
643
+ // Backbone.Controller
644
+ // -------------------
645
+
646
+ // Controllers map faux-URLs to actions, and fire events when routes are
647
+ // matched. Creating a new one sets its `routes` hash, if not set statically.
648
+ Backbone.Controller = function(options) {
649
+ options || (options = {});
650
+ if (options.routes) this.routes = options.routes;
651
+ this._bindRoutes();
652
+ this.initialize(options);
653
+ };
654
+
655
+ // Cached regular expressions for matching named param parts and splatted
656
+ // parts of route strings.
657
+ var namedParam = /:([\w\d]+)/g;
658
+ var splatParam = /\*([\w\d]+)/g;
659
+ var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
660
+
661
+ // Set up all inheritable **Backbone.Controller** properties and methods.
662
+ _.extend(Backbone.Controller.prototype, Backbone.Events, {
663
+
664
+ // Initialize is an empty function by default. Override it with your own
665
+ // initialization logic.
666
+ initialize : function(){},
667
+
668
+ // Manually bind a single named route to a callback. For example:
669
+ //
670
+ // this.route('search/:query/p:num', 'search', function(query, num) {
671
+ // ...
672
+ // });
673
+ //
674
+ route : function(route, name, callback) {
675
+ Backbone.history || (Backbone.history = new Backbone.History);
676
+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
677
+ Backbone.history.route(route, _.bind(function(hash) {
678
+ var args = this._extractParameters(route, hash);
679
+ callback.apply(this, args);
680
+ this.trigger.apply(this, ['route:' + name].concat(args));
681
+ }, this));
682
+ },
683
+
684
+ // Simple proxy to `Backbone.history` to save a fragment into the history,
685
+ // without triggering routes.
686
+ saveLocation : function(hash) {
687
+ Backbone.history.saveLocation(hash);
688
+ },
689
+
690
+ // Bind all defined routes to `Backbone.history`. We have to reverse the
691
+ // order of the routes here to support behavior where the most general
692
+ // routes can be defined at the bottom of the route map.
693
+ _bindRoutes : function() {
694
+ if (!this.routes) return;
695
+ var routes = [];
696
+ for (var route in this.routes) {
697
+ routes.unshift([route, this.routes[route]]);
698
+ }
699
+ for (var i = 0, l = routes.length; i < l; i++) {
700
+ this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
701
+ }
702
+ },
703
+
704
+ // Convert a route string into a regular expression, suitable for matching
705
+ // against the current location hash.
706
+ _routeToRegExp : function(route) {
707
+ route = route.replace(escapeRegExp, "\\$&")
708
+ .replace(namedParam, "([^\/]*)")
709
+ .replace(splatParam, "(.*?)");
710
+ return new RegExp('^' + route + '$');
711
+ },
712
+
713
+ // Given a route, and a URL fragment that it matches, return the array of
714
+ // extracted parameters.
715
+ _extractParameters : function(route, hash) {
716
+ return route.exec(hash).slice(1);
717
+ }
718
+
719
+ });
720
+
721
+ // Backbone.History
722
+ // ----------------
723
+
724
+ // Handles cross-browser history management, based on URL hashes. If the
725
+ // browser does not support `onhashchange`, falls back to polling.
726
+ Backbone.History = function() {
727
+ this.handlers = [];
728
+ _.bindAll(this, 'checkUrl');
729
+ };
730
+
731
+ // Cached regex for cleaning hashes.
732
+ var hashStrip = /^#*!?/;
733
+
734
+ // Cached regex for detecting MSIE.
735
+ var isExplorer = /msie [\w.]+/;
736
+
737
+ // Has the history handling already been started?
738
+ var historyStarted = false;
739
+
740
+ // Set up all inheritable **Backbone.History** properties and methods.
741
+ _.extend(Backbone.History.prototype, {
742
+
743
+ // The default interval to poll for hash changes, if necessary, is
744
+ // twenty times a second.
745
+ interval: 50,
746
+
747
+ // Get the cross-browser normalized URL fragment.
748
+ getHash : function(loc) {
749
+ return (loc || window.location).hash.replace(hashStrip, '');
750
+ },
751
+
752
+ // Start the hash change handling, returning `true` if the current URL matches
753
+ // an existing route, and `false` otherwise.
754
+ start : function() {
755
+ if (historyStarted) throw new Error("Backbone.history has already been started");
756
+ var hash = this.getHash();
757
+ var docMode = document.documentMode;
758
+ var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
759
+ if (oldIE) {
760
+ this.iframe = $('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
761
+ this.saveLocation(hash);
762
+ }
763
+ if ('onhashchange' in window && !oldIE) {
764
+ $(window).bind('hashchange', this.checkUrl);
765
+ } else {
766
+ setInterval(this.checkUrl, this.interval);
767
+ }
768
+ this.hash = hash;
769
+ historyStarted = true;
770
+ return this.loadUrl();
771
+ },
772
+
773
+ // Add a route to be tested when the hash changes. Routes added later may
774
+ // override previous routes.
775
+ route : function(route, callback) {
776
+ this.handlers.unshift({route : route, callback : callback});
777
+ },
778
+
779
+ // Checks the current URL to see if it has changed, and if it has,
780
+ // calls `loadUrl`, normalizing across the hidden iframe.
781
+ checkUrl : function() {
782
+ var hash = this.getHash();
783
+ if (hash == this.hash && this.iframe) hash = this.getHash(this.iframe.location);
784
+ if (hash == this.hash || hash == decodeURIComponent(this.hash)) return false;
785
+ if (this.iframe) this.saveLocation(hash);
786
+ this.hash = hash;
787
+ this.loadUrl();
788
+ },
789
+
790
+ // Attempt to load the current URL fragment. If a route succeeds with a
791
+ // match, returns `true`. If no defined routes matches the fragment,
792
+ // returns `false`.
793
+ loadUrl : function() {
794
+ var hash = this.hash;
795
+ var matched = _.any(this.handlers, function(handler) {
796
+ if (handler.route.test(hash)) {
797
+ handler.callback(hash);
798
+ return true;
799
+ }
800
+ });
801
+ return matched;
802
+ },
803
+
804
+ // Save a fragment into the hash history. You are responsible for properly
805
+ // URL-encoding the fragment in advance. This does not trigger
806
+ // a `hashchange` event.
807
+ saveLocation : function(hash) {
808
+ hash = (hash || '').replace(hashStrip, '');
809
+ if (this.hash == hash) return;
810
+ window.location.hash = this.hash = hash;
811
+ if (this.iframe && (hash != this.getHash(this.iframe.location))) {
812
+ this.iframe.document.open().close();
813
+ this.iframe.location.hash = hash;
814
+ }
815
+ }
816
+
817
+ });
818
+
819
+ // Backbone.View
820
+ // -------------
821
+
822
+ // Creating a Backbone.View creates its initial element outside of the DOM,
823
+ // if an existing element is not provided...
824
+ Backbone.View = function(options) {
825
+ this.cid = _.uniqueId('view');
826
+ this._configure(options || {});
827
+ this._ensureElement();
828
+ this.delegateEvents();
829
+ this.initialize(options);
830
+ };
831
+
832
+ // Element lookup, scoped to DOM elements within the current view.
833
+ // This should be prefered to global lookups, if you're dealing with
834
+ // a specific view.
835
+ var selectorDelegate = function(selector) {
836
+ return $(selector, this.el);
837
+ };
838
+
839
+ // Cached regex to split keys for `delegate`.
840
+ var eventSplitter = /^(\S+)\s*(.*)$/;
841
+
842
+ // List of view options to be merged as properties.
843
+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
844
+
845
+ // Set up all inheritable **Backbone.View** properties and methods.
846
+ _.extend(Backbone.View.prototype, Backbone.Events, {
847
+
848
+ // The default `tagName` of a View's element is `"div"`.
849
+ tagName : 'div',
850
+
851
+ // Attach the `selectorDelegate` function as the `$` property.
852
+ $ : selectorDelegate,
853
+
854
+ // Initialize is an empty function by default. Override it with your own
855
+ // initialization logic.
856
+ initialize : function(){},
857
+
858
+ // **render** is the core function that your view should override, in order
859
+ // to populate its element (`this.el`), with the appropriate HTML. The
860
+ // convention is for **render** to always return `this`.
861
+ render : function() {
862
+ return this;
863
+ },
864
+
865
+ // Remove this view from the DOM. Note that the view isn't present in the
866
+ // DOM by default, so calling this method may be a no-op.
867
+ remove : function() {
868
+ $(this.el).remove();
869
+ return this;
870
+ },
871
+
872
+ // For small amounts of DOM Elements, where a full-blown template isn't
873
+ // needed, use **make** to manufacture elements, one at a time.
874
+ //
875
+ // var el = this.make('li', {'class': 'row'}, this.model.escape('title'));
876
+ //
877
+ make : function(tagName, attributes, content) {
878
+ var el = document.createElement(tagName);
879
+ if (attributes) $(el).attr(attributes);
880
+ if (content) $(el).html(content);
881
+ return el;
882
+ },
883
+
884
+ // Set callbacks, where `this.callbacks` is a hash of
885
+ //
886
+ // *{"event selector": "callback"}*
887
+ //
888
+ // {
889
+ // 'mousedown .title': 'edit',
890
+ // 'click .button': 'save'
891
+ // }
892
+ //
893
+ // pairs. Callbacks will be bound to the view, with `this` set properly.
894
+ // Uses event delegation for efficiency.
895
+ // Omitting the selector binds the event to `this.el`.
896
+ // This only works for delegate-able events: not `focus`, `blur`, and
897
+ // not `change`, `submit`, and `reset` in Internet Explorer.
898
+ delegateEvents : function(events) {
899
+ if (!(events || (events = this.events))) return;
900
+ $(this.el).unbind('.delegateEvents' + this.cid);
901
+ for (var key in events) {
902
+ var methodName = events[key];
903
+ var match = key.match(eventSplitter);
904
+ var eventName = match[1], selector = match[2];
905
+ var method = _.bind(this[methodName], this);
906
+ eventName += '.delegateEvents' + this.cid;
907
+ if (selector === '') {
908
+ $(this.el).bind(eventName, method);
909
+ } else {
910
+ $(this.el).delegate(selector, eventName, method);
911
+ }
912
+ }
913
+ },
914
+
915
+ // Performs the initial configuration of a View with a set of options.
916
+ // Keys with special meaning *(model, collection, id, className)*, are
917
+ // attached directly to the view.
918
+ _configure : function(options) {
919
+ if (this.options) options = _.extend({}, this.options, options);
920
+ for (var i = 0, l = viewOptions.length; i < l; i++) {
921
+ var attr = viewOptions[i];
922
+ if (options[attr]) this[attr] = options[attr];
923
+ }
924
+ this.options = options;
925
+ },
926
+
927
+ // Ensure that the View has a DOM element to render into.
928
+ // If `this.el` is a string, pass it through `$()`, take the first
929
+ // matching element, and re-assign it to `el`. Otherwise, create
930
+ // an element from the `id`, `className` and `tagName` proeprties.
931
+ _ensureElement : function() {
932
+ if (!this.el) {
933
+ var attrs = this.attributes || {};
934
+ if (this.id) attrs.id = this.id;
935
+ if (this.className) attrs['class'] = this.className;
936
+ this.el = this.make(this.tagName, attrs);
937
+ } else if (_.isString(this.el)) {
938
+ this.el = $(this.el).get(0);
939
+ }
940
+ }
941
+
942
+ });
943
+
944
+ // The self-propagating extend function that Backbone classes use.
945
+ var extend = function (protoProps, classProps) {
946
+ var child = inherits(this, protoProps, classProps);
947
+ child.extend = this.extend;
948
+ return child;
949
+ };
950
+
951
+ // Set up inheritance for the model, collection, and view.
952
+ Backbone.Model.extend = Backbone.Collection.extend =
953
+ Backbone.Controller.extend = Backbone.View.extend = extend;
954
+
955
+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
956
+ var methodMap = {
957
+ 'create': 'POST',
958
+ 'update': 'PUT',
959
+ 'delete': 'DELETE',
960
+ 'read' : 'GET'
961
+ };
962
+
963
+ // Backbone.sync
964
+ // -------------
965
+
966
+ // Override this function to change the manner in which Backbone persists
967
+ // models to the server. You will be passed the type of request, and the
968
+ // model in question. By default, uses makes a RESTful Ajax request
969
+ // to the model's `url()`. Some possible customizations could be:
970
+ //
971
+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
972
+ // * Send up the models as XML instead of JSON.
973
+ // * Persist models via WebSockets instead of Ajax.
974
+ //
975
+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
976
+ // as `POST`, with a `_method` parameter containing the true HTTP method,
977
+ // as well as all requests with the body as `application/x-www-form-urlencoded` instead of
978
+ // `application/json` with the model in a param named `model`.
979
+ // Useful when interfacing with server-side languages like **PHP** that make
980
+ // it difficult to read the body of `PUT` requests.
981
+ Backbone.sync = function(method, model, options) {
982
+ var type = methodMap[method];
983
+
984
+ // Default JSON-request options.
985
+ var params = _.extend({
986
+ type: type,
987
+ dataType: 'json',
988
+ processData: false
989
+ }, options);
990
+
991
+ // Ensure that we have a URL.
992
+ if (!params.url) {
993
+ params.url = getUrl(model) || urlError();
994
+ }
995
+
996
+ // Ensure that we have the appropriate request data.
997
+ if (!params.data && model && (method == 'create' || method == 'update')) {
998
+ params.contentType = 'application/json';
999
+ params.data = JSON.stringify(model.toJSON());
1000
+ }
1001
+
1002
+ // For older servers, emulate JSON by encoding the request into an HTML-form.
1003
+ if (Backbone.emulateJSON) {
1004
+ params.contentType = 'application/x-www-form-urlencoded';
1005
+ params.processData = true;
1006
+ params.data = params.data ? {model : params.data} : {};
1007
+ }
1008
+
1009
+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1010
+ // And an `X-HTTP-Method-Override` header.
1011
+ if (Backbone.emulateHTTP) {
1012
+ if (type === 'PUT' || type === 'DELETE') {
1013
+ if (Backbone.emulateJSON) params.data._method = type;
1014
+ params.type = 'POST';
1015
+ params.beforeSend = function(xhr) {
1016
+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
1017
+ };
1018
+ }
1019
+ }
1020
+
1021
+ // Make the request.
1022
+ return $.ajax(params);
1023
+ };
1024
+
1025
+ // Helpers
1026
+ // -------
1027
+
1028
+ // Shared empty constructor function to aid in prototype-chain creation.
1029
+ var ctor = function(){};
1030
+
1031
+ // Helper function to correctly set up the prototype chain, for subclasses.
1032
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
1033
+ // class properties to be extended.
1034
+ var inherits = function(parent, protoProps, staticProps) {
1035
+ var child;
1036
+
1037
+ // The constructor function for the new subclass is either defined by you
1038
+ // (the "constructor" property in your `extend` definition), or defaulted
1039
+ // by us to simply call `super()`.
1040
+ if (protoProps && protoProps.hasOwnProperty('constructor')) {
1041
+ child = protoProps.constructor;
1042
+ } else {
1043
+ child = function(){ return parent.apply(this, arguments); };
1044
+ }
1045
+
1046
+ // Inherit class (static) properties from parent.
1047
+ _.extend(child, parent);
1048
+
1049
+ // Set the prototype chain to inherit from `parent`, without calling
1050
+ // `parent`'s constructor function.
1051
+ ctor.prototype = parent.prototype;
1052
+ child.prototype = new ctor();
1053
+
1054
+ // Add prototype properties (instance properties) to the subclass,
1055
+ // if supplied.
1056
+ if (protoProps) _.extend(child.prototype, protoProps);
1057
+
1058
+ // Add static properties to the constructor function, if supplied.
1059
+ if (staticProps) _.extend(child, staticProps);
1060
+
1061
+ // Correctly set child's `prototype.constructor`.
1062
+ child.prototype.constructor = child;
1063
+
1064
+ // Set a convenience property in case the parent's prototype is needed later.
1065
+ child.__super__ = parent.prototype;
1066
+
1067
+ return child;
1068
+ };
1069
+
1070
+ // Helper function to get a URL from a Model or Collection as a property
1071
+ // or as a function.
1072
+ var getUrl = function(object) {
1073
+ if (!(object && object.url)) return null;
1074
+ return _.isFunction(object.url) ? object.url() : object.url;
1075
+ };
1076
+
1077
+ // Throw an error when a URL is needed, and none is supplied.
1078
+ var urlError = function() {
1079
+ throw new Error("A 'url' property or function must be specified");
1080
+ };
1081
+
1082
+ // Wrap an optional error callback with a fallback error event.
1083
+ var wrapError = function(onError, model, options) {
1084
+ return function(resp) {
1085
+ if (onError) {
1086
+ onError(model, resp, options);
1087
+ } else {
1088
+ model.trigger('error', model, resp, options);
1089
+ }
1090
+ };
1091
+ };
1092
+
1093
+ // Helper function to escape a string for HTML rendering.
1094
+ var escapeHTML = function(string) {
1095
+ return string.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
1096
+ };
1097
+
1098
+ }).call(this);