-
Notifications
You must be signed in to change notification settings - Fork 3
/
xview.js
441 lines (354 loc) · 10.4 KB
/
xview.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/**
* XView
*
* Easily create hierarchical structures
* An XView can make multiple child views, which can have multiple child views.
* When removing a parent view, children are removed automatically.
*
* Easy templating
* Add a template string to the template property, and optionally add unwrap: true
* to avoid having Backbone wrap it in an extra tag. This can make templating
* and styling easier.
*/
/**
* Factory
*/
;(function(factory) {
// AMD
if (typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
}
//CommonJS
else if (typeof exports !== 'undefined') {
factory(require('underscore'), require('backbone'));
}
//Globals
else {
factory(_, Backbone);
}
}(function(_, Backbone) {
/**
* Main view
*/
var XView = Backbone.View.extend({
//Helpers functions (and properties) that are sent to the template on render
renderHelpers: {},
/**
* Constructor
*
* @param {Object} [options]
* @param {View} [options.parent] Parent view (Passed automatically when using XView#addView)
* @param {Function} [options.template] Compiled template, e.g. the result of _.template('<div></div>')
* @param {Boolean} [options.unwrap] Whether to use only the template, so that there isn't an extra tag around the template contents. NOTE: If using unwrap, there must be one single parent element in the template.
*/
constructor: function(options) {
options = options || {};
this.parent = options.parent;
this.children = {};
if (options.template) this.template = options.template;
if (options.unwrap) this.unwrap = options.unwrap;
this.rendered = false;
Backbone.View.prototype.constructor.call(this, options);
},
/**
* Returns the data to be sent to the template.
* Default implementation is to return the model JSON object,
* but this method can be overridden to return any other data
*
* This can also be overridden with a simple object rather than function.
*
* @return {Object} The data to send to the template
*/
templateData: function() {
return this.model ? this.model.toJSON() : {};
},
/**
* Adds a child view.
* If a selector is specified, the view will be appended to that part of the template.
*
* @param {String} [selector]
* @param {Object} [options]
* @param {Mixed} [options.id] For fine-grained control if you need to access views after being added. Not necessary in most cases.
* @param {View} view
* @return {View}
*/
addView: function(selector, options, view) {
//Normalise arguments
if (arguments.length == 2) { //selector, view
view = options;
options = {};
} else if (arguments.length == 1) { //view
view = selector;
options = {};
selector = null;
}
//Generate an ID if not given
var id = options.id || _.uniqueId();
//Add to the list of children
var child = this.children[id] = {
selector: selector,
view: view
};
//If this view is already rendered, add the child automatically
if (this.rendered) {
this.renderView(id);
}
return view;
},
/**
* Get a child view by ID
*
* @param {Mixed} id The child view ID
*
* @return {View|Null}
*/
getView: function(id) {
var child = this.children[id];
return child ? child.view : null;
},
/**
* Creates the HTML from the template function
*
* @param {Object} data
*
* @return {String}
*/
renderTemplate: function(data) {
return this.template(data);
},
/**
* Renders the main element with the template.
*
* If using a template and the 'unwrap' property is true then the template HTML will not be wrapped
* in an extra tag. This can make editing and styling templates easier.
*
* @return {View} Returns self
*/
render: function() {
if (this.template) {
var html = '';
//Get data for template
var data = _.result(this, 'templateData');
//Add template helpers
data = _.extend({}, this.renderHelpers, data);
//Render HTML
html = Backbone.$(this.renderTemplate(data));
//If using unwrap and this is an update, only replace the main element contents
//This ensures the view that's actually in the DOM is updated
if (this.unwrap) {
if (!this.rendered) {
this.setElement(html);
} else {
this.$el.html(html.html());
this.delegateEvents();
}
} else {
this.$el.html(html);
}
}
this.renderViews();
if (this.onRender) this.onRender();
this.rendered = true;
return this;
},
/**
* Render all child views
*/
renderViews: function() {
var self = this,
ids = _.keys(this.children);
_.each(ids, _.bind(self.renderView, this));
},
/**
* Renders a child view and adds it to it's locations in the parent element
*
* @param {Mixed} id The child view ID
*/
renderView: function(id) {
var child = this.children[id];
var selector = child.selector,
view = child.view,
$el = null;
view.render();
//Decide where the child view is going
if (selector) {
$el = this.$el.find(selector);
} else {
$el = this.$el;
}
$el.append(view.el);
},
/**
* Close and remove all child views
*/
removeViews: function() {
var self = this,
ids = _.keys(this.children);
_.each(ids, _.bind(self.removeView, this));
},
/**
* Close and remove a child view
*
* @param {Mixed} id Child view ID
*/
removeView: function(id) {
var children = this.children,
child = children[id];
if (!child) return;
child.view.remove();
delete children[id];
},
/**
* Closes child views then this one, removes event listeners etc.
*/
remove: function() {
this.removeViews();
Backbone.View.prototype.remove.call(this);
}
});
/**
* CollectionView
* Renders a list of ItemViews representing a collection
*/
var CollectionView = XView.extend({
tagName: 'ul',
//Selector string for where items will be inserted. If not set, will default to the root element
listSelector: null,
//View to show when if collection is empty
fallbackView: null,
//View to show when loading
loadingView: null,
/**
* Constructor
*
* @param {Object} options
* @param {Collection} options.collection Collection to render
* @param {XView} options.itemView Constructor (not instance) for an item view
*/
constructor: function(options) {
XView.prototype.constructor.call(this, options);
options = options || {};
if (options.collection) this.collection = options.collection;
if (!this.collection) throw new Error('collection is required');
if (options.itemView) this.itemView = options.itemView;
if (!this.itemView) throw new Error('itemView is required');
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'remove', this.removeItem);
this.listenTo(this.collection, 'reset', this.resetItems);
this.listenTo(this.collection, 'request', this.onRequest);
this.listenTo(this.collection, 'sync', this.onSync);
},
render: function() {
XView.prototype.render.call(this);
//Show loading if collection is being fetched
if (this.isLoading) {
this.showLoading();
this.hideFallback();
}
//Not loading; show items
else {
this.hideLoading();
this.resetItems();
}
return this;
},
/**
* Shows the fallback view
*/
showFallback: function() {
if (this.getView('fallback')) return;
var view = this.fallbackView;
if (!view) return;
//Create view instance if required
if (!(view instanceof Backbone.View)) {
view = new view();
}
this.addView(this.listSelector, { id: 'fallback' }, view);
},
/**
* Hides the fallback view
*/
hideFallback: function() {
this.removeView('fallback');
},
/**
* Shows the loading view
*/
showLoading: function() {
if (this.getView('loading')) return;
var view = this.loadingView;
if (!view) return;
//Create view instance if required
if (!(view instanceof Backbone.View)) {
view = new view();
}
this.addView(this.listSelector, { id: 'loading' }, view);
},
/**
* Hides the loading view
*/
hideLoading: function() {
this.removeView('loading');
},
/**
* Renders a new model
*
* @param {Model} model
*/
addItem: function(model) {
var view = new this.itemView({
model: model
});
this.addView(this.listSelector || null, { id: model.cid }, view);
},
/**
* @param {Model} model
*/
removeItem: function(model) {
this.removeView(model.cid);
},
/**
* Removes existing item views and adds the current collection contents
*/
resetItems: function() {
this.removeViews();
this.collection.each(_.bind(this.addItem, this));
//Show fallback if there are no items
if (!this.collection.length) {
this.showFallback();
} else {
this.hideFallback();
}
},
/**
* Callback for when a request has started, i.e. collection is in loading state
*/
onRequest: function() {
this.isLoading = true;
//Show loading if there are no items
if (!this.collection.length) {
this.showLoading();
}
},
/**
* Callback for when a request has ended, i.e. collection is not in loading state
*/
onSync: function() {
//Hide loading
this.isLoading = false;
this.hideLoading();
//Show fallback if there are no items
if (!this.collection.length) {
this.showFallback();
}
}
});
/**
* Exports
*/
XView.Collection = CollectionView;
Backbone.XView = XView;
//For use in NodeJS
if (typeof module != 'undefined') module.exports = XView;
return Backbone.XView;
}));