forked from AmpersandJS/ampersand-view
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ampersand-view.js
362 lines (334 loc) · 12.5 KB
/
ampersand-view.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
var State = require('ampersand-state');
var CollectionView = require('ampersand-collection-view');
var domify = require('domify');
var _ = require('underscore');
var events = require('events-mixin');
var matches = require('matches-selector');
var bindings = require('ampersand-dom-bindings');
var getPath = require('get-object-path');
function View(attrs) {
this.cid = _.uniqueId('view');
attrs || (attrs = {});
var parent = attrs.parent;
delete attrs.parent;
BaseState.call(this, attrs, {init: false, parent: parent});
this.on('change:el', this._handleElementChange, this);
this._parsedBindings = bindings(this.bindings);
this._initializeBindings();
if (attrs.el && !this.autoRender) {
this._handleElementChange();
}
this._initializeSubviews();
this.initialize.apply(this, arguments);
this.set(_.pick(attrs, viewOptions));
if (this.autoRender && this.template) {
this.render();
}
}
var BaseState = State.extend({
dataTypes: {
element: {
set: function (newVal) {
return {
val: newVal,
type: newVal instanceof Element ? 'element' : typeof newVal
};
},
compare: function (el1, el2) {
return el1 === el2;
}
},
collection: {
set: function (newVal) {
return {
val: newVal,
type: newVal && newVal.isCollection ? 'collection' : typeof newVal
};
},
compare: function (currentVal, newVal) {
return currentVal === newVal;
}
}
},
props: {
model: 'state',
el: 'element',
collection: 'collection'
},
derived: {
rendered: {
deps: ['el'],
fn: function () {
return !!this.el;
}
},
hasData: {
deps: ['model'],
fn: function () {
return !!this.model;
}
}
}
});
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el'];
View.prototype = Object.create(BaseState.prototype);
// Set up all inheritable properties and methods.
_.extend(View.prototype, {
// ## query
// Get an single element based on CSS selector scoped to this.el
// if you pass an empty string it return `this.el`.
// If you pass an element we just return it back.
// This lets us use `get` to handle cases where users
// can pass a selector or an already selected element.
query: function (selector) {
if (!selector) return this.el;
if (typeof selector === 'string') {
if (matches(this.el, selector)) return this.el;
return this.el.querySelector(selector) || undefined;
}
return selector;
},
// ## queryAll
// Returns an array of elements based on CSS selector scoped to this.el
// if you pass an empty string it return `this.el`. Also includes root
// element.
queryAll: function (selector) {
var res = [];
if (!this.el) return res;
if (selector === '') return [this.el];
if (matches(this.el, selector)) res.push(this.el);
return res.concat(Array.prototype.slice.call(this.el.querySelectorAll(selector)));
},
// ## queryByHook
// Convenience method for fetching element by it's `data-hook` attribute.
// Also tries to match against root element.
// Also supports matching 'one' of several space separated hooks.
queryByHook: function (hook) {
return this.query('[data-hook~="' + hook + '"]');
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function () {},
// **render** is the core function that your view can override, its job is
// to populate its element (`this.el`), with the appropriate HTML.
render: function () {
this.renderWithTemplate(this);
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable events listeners.
remove: function () {
var parsedBindings = this._parsedBindings;
if (this.el && this.el.parentNode) this.el.parentNode.removeChild(this.el);
_.chain(this._subviews).flatten().invoke('remove');
this.stopListening();
// TODO: Not sure if this is actually necessary.
// Just trying to de-reference this potentially large
// amount of generated functions to avoid memory leaks.
_.each(parsedBindings, function (properties, modelName) {
_.each(properties, function (value, key) {
delete parsedBindings[modelName][key];
});
delete parsedBindings[modelName];
});
this.trigger('remove', this);
return this;
},
// Change the view's element (`this.el` property), including event
// re-delegation.
_handleElementChange: function (element, delegate) {
if (this.eventManager) this.eventManager.unbind();
this.eventManager = events(this.el, this);
this.delegateEvents();
this._applyBindingsForKey();
return this;
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save',
// 'click .open': function (e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
// This only works for delegate-able events: not `focus`, `blur`, and
// not `change`, `submit`, and `reset` in Internet Explorer.
delegateEvents: function (events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
this.eventManager.bind(key, events[key]);
}
return this;
},
// Clears all callbacks previously bound to the view with `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function () {
this.eventManager.unbind();
return this;
},
// ## registerSubview
// Pass it a view. This can be anything with a `remove` method
registerSubview: function (view) {
// Storage for our subviews.
this._subviews || (this._subviews = []);
this._subviews.push(view);
// If view has an 'el' it's a single view not
// an array of views registered by renderCollection
// so we store a reference to the parent view.
if (view.el) view.parent = this;
return view;
},
// ## renderSubview
// Pass it a view instance and a container element
// to render it in. It's `remove` method will be called
// when the parent view is destroyed.
renderSubview: function (view, container) {
if (typeof container === 'string') {
container = this.query(container);
}
this.registerSubview(view);
view.render();
container.appendChild(view.el);
return view;
},
_applyBindingsForKey: function (name) {
if (!this.el) return;
var fns = this._parsedBindings.getGrouped(name);
var item;
for (item in fns) {
fns[item].forEach(function (fn) {
fn(this.el, getPath(this, item), _.last(item.split('.')));
}, this);
}
},
_initializeBindings: function () {
if (!this.bindings) return;
this.on('all', function (eventName) {
if (eventName.slice(0, 7) === 'change:') {
this._applyBindingsForKey(eventName.split(':')[1]);
}
}, this);
},
// ## _initializeSubviews
// this is called at setup and grabs declared subviews
_initializeSubviews: function () {
if (!this.subviews) return;
for (var item in this.subviews) {
this._parseSubview(this.subviews[item], item);
}
},
// ## _parseSubview
// helper for parsing out the subview declaration and registering
// the `waitFor` if need be.
_parseSubview: function (subview, name) {
var self = this;
var opts = {
selector: subview.container || '[data-hook="' + subview.hook + '"]',
waitFor: subview.waitFor || '',
prepareView: subview.prepareView || function (el) {
return new subview.constructor({
el: el,
parent: self
});
}
};
function action() {
var el, subview;
// if not rendered or we can't find our element, stop here.
if (!this.el || !(el = this.query(opts.selector))) return;
if (!opts.waitFor || getPath(this, opts.waitFor)) {
subview = this[name] = opts.prepareView.call(this, el);
subview.render();
this.registerSubview(subview);
this.off('change', action);
}
}
// we listen for main `change` items
this.on('change', action, this);
},
// Shortcut for doing everything we need to do to
// render and fully replace current root element.
// Either define a `template` property of your view
// or pass in a template directly.
// The template can either be a string or a function.
// If it's a function it will be passed the `context`
// argument.
renderWithTemplate: function (context, templateArg) {
var template = templateArg || this.template;
if (!template) throw new Error('Template string or function needed.');
var newDom = _.isString(template) ? template : template(context || this);
if (_.isString(newDom)) newDom = domify(newDom);
var parent = this.el && this.el.parentNode;
if (parent) parent.replaceChild(newDom, this.el);
if (newDom.nodeName === '#document-fragment') throw new Error('Views can only have one root element.');
this.el = newDom;
return this;
},
// ## cacheElements
// This is a shortcut for adding reference to specific elements within your view for
// access later. This avoids excessive DOM queries and makes it easier to update
// your view if your template changes.
//
// In your `render` method. Use it like so:
//
// render: function () {
// this.basicRender();
// this.cacheElements({
// pages: '#pages',
// chat: '#teamChat',
// nav: 'nav#views ul',
// me: '#me',
// cheatSheet: '#cheatSheet',
// omniBox: '#awesomeSauce'
// });
// }
//
// Then later you can access elements by reference like so: `this.pages`, or `this.chat`.
cacheElements: function (hash) {
for (var item in hash) {
this[item] = this.query(hash[item]);
}
},
// ## listenToAndRun
// Shortcut for registering a listener for a model
// and also triggering it right away.
listenToAndRun: function (object, events, handler) {
var bound = _.bind(handler, this);
this.listenTo(object, events, bound);
bound();
},
// ## animateRemove
// Placeholder for if you want to do something special when they're removed.
// For example fade it out, etc.
// Any override here should call `.remove()` when done.
animateRemove: function () {
this.remove();
},
// ## renderCollection
// Method for rendering a collections with individual views.
// Just pass it the collection, and the view to use for the items in the
// collection. The collectionView is returned.
renderCollection: function (collection, ViewClass, container, opts) {
var containerEl = (typeof container === 'string') ? this.query(container) : container;
var config = _.extend({
collection: collection,
el: containerEl,
view: ViewClass
}, opts);
var collectionView = new CollectionView(config);
collectionView.render();
return this.registerSubview(collectionView);
}
});
View.extend = BaseState.extend;
module.exports = View;