forked from FormidableLabs/handlebones
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlebones.js
533 lines (499 loc) · 15.8 KB
/
handlebones.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// Handlebones 0.0.1
//
// (c) 2014 Formidable Labs Inc.
// Handlebones may be freely distributed under the MIT license.
// For all details and documentation:
// http://handlebonesjs.org
//
// Handlebones is a minimalist version of Thorax:
// http://thoraxjs.org/
// Original copyright notice follows.
//
// ###
//
// Copyright (c) 2011-2013 @WalmartLabs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
(function (root, factory) {
// Set up Handlebones appropriately for the environment. Start with AMD.
if (typeof define === "function" && define.amd) {
define([
"underscore",
"backbone",
"handlebars",
"jquery",
"exports"
], function (_, Backbone, Handlebars, $, exports) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Handlebones = factory(root, exports, _, Backbone, Handlebars, $);
});
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
/* global exports */
} else if (typeof exports !== "undefined") {
var _ = require("underscore"),
Backbone = require("backbone"),
Handlebars = require("handlebars");
factory(root, exports, _, Backbone, Handlebars);
// Finally, as a browser global.
} else {
root.Handlebones = factory(
root,
{},
root._,
root.Backbone,
root.Handlebars,
(root.jQuery || root.Zepto || root.ender || root.$)
);
}
})(this, function (root, Handlebones, _, Backbone, Handlebars, $) {
Handlebones.VERSION = "0.0.1";
var viewNameAttributeName = "data-view-name",
viewCidAttributeName = "data-view-cid",
viewPlaceholderAttributeName = "data-view-tmp",
modelCidAttributeName = "data-model-cid",
viewsIndexedByCid = {},
isIE11 = !!navigator.userAgent.match(/Trident\/7\./),
isIE = isIE11 || (/msie [\w.]+/).exec(navigator.userAgent.toLowerCase()),
hasDOMLib = typeof $ !== "undefined" && $.fn;
// DOM
function hasClassName(name) {
return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(this.className);
}
function addClassName(name) {
if (!hasClassName.call(this, name)) {
this.className = this.className ? [this.className, name].join(" ") : name;
}
}
function removeClassName(name) {
if (hasClassName.call(this, name)) {
var className = this.className,
regexp = new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g");
this.className = className.replace(regexp, "");
}
}
// View
function triggerReady(view) {
if (!view._isReady) {
view.trigger("ready");
}
}
function onReady() {
if (!this._isReady) {
this._isReady = true;
_.each(this.children, triggerReady);
}
}
function configureView() {
this._renderCount = 0;
this.children = {};
viewsIndexedByCid[this.cid] = this;
this.listenTo(this, "ready", onReady);
}
function ensureRendered() {
if (!this._renderCount) {
this.render();
}
}
function replaceHTML(html) {
// Normalize Handlebars.SafeString
if (html && html.string) {
html = html.string;
}
if (hasDOMLib) {
// We want to pull our elements out of the tree if we are under jQuery
// or IE as both have the tendancy to mangle the elements we want to reuse
// on cleanup. This could leak event binds if users are performing custom binds
// but this generally not recommended.
if (this._renderCount && (isIE || ($.fn && $.fn.jquery))) {
while (this.el.hasChildNodes()) {
this.el.removeChild(this.el.childNodes[0]);
}
}
this.$el.empty();
this.$el.append(html);
} else {
this.el.innerHTML = html;
}
}
Handlebones.View = Backbone.View.extend({
template: Handlebars.VM.noop,
render: function (html) {
var output;
if (_.isFunction(html)) {
output = html(this.context());
} else if (_.isString(html)) {
output = html;
} else {
output = this.template(this.context());
}
replaceHTML.call(this, output);
appendChildViews.call(this);
++this._renderCount;
this.trigger("render");
return this;
},
context: function () {
return this;
},
appendTo: function (el) {
ensureRendered.call(this);
// allow for a custom dom insertion operation
if (_.isFunction(el)) {
el();
} else {
el.appendChild(this.el);
}
triggerReady(this);
return this;
},
addChild: function (view) {
if (this.children[view.cid]) {
return view;
}
view.parent = this;
this.children[view.cid] = view;
if (this._isReady) {
triggerReady(view);
}
return view;
},
removeChild: function (view) {
delete view.parent;
delete this.children[view.cid];
return view;
},
remove: function () {
_.each(this.children, function (view) {
this.removeChild(view);
}, this);
delete viewsIndexedByCid[this.cid];
if (this.name) {
this.el.removeAttribute(viewNameAttributeName);
}
this.el.removeAttribute(viewCidAttributeName);
this.trigger("remove");
return Backbone.View.prototype.remove.apply(this, arguments);
},
// Private and undocumented methods
toString: function () {
return "[object Handlebones.View." + (this.name || this.cid) + "]";
},
setElement : function () {
var response = Backbone.View.prototype.setElement.apply(this, arguments);
if (this.name) {
this.el.setAttribute(viewNameAttributeName, this.name);
}
this.el.setAttribute(viewCidAttributeName, this.cid);
return response;
},
// So developers don't need to call parent initialize, use _ensureElement
// hook to configure the view
_ensureElement: function () {
configureView.call(this);
return Backbone.View.prototype._ensureElement.call(this);
},
_useDocumentFragment: function (callback) {
var el = this.el;
this.el = document.createDocumentFragment();
callback.call(this);
el.appendChild(this.el);
this.el = el;
}
});
// LayoutView
Handlebones.LayoutView = Handlebones.View.extend({
render: function () {
// Basically a noop
++this._renderCount;
this.trigger("render");
return this;
},
setView: function (view, callback) {
var oldView = this._view,
append,
remove;
if (view === oldView) {
return this;
}
remove = _.bind(function () {
if (oldView) {
oldView.remove();
this.removeChild(oldView);
}
}, this);
append = _.bind(function () {
this._view = view;
if (view) {
ensureRendered.call(view);
this.addChild(view);
this._view.appendTo(this.el);
}
}, this);
if (!callback) {
remove();
append();
} else {
callback(view, oldView, append, remove);
}
return this;
},
getView: function () {
return this._view;
}
});
// ModelView
Handlebones.ModelView = Handlebones.View.extend({
initialize: function () {
this.listenTo(this.model, "change", this.render);
},
context: function () {
return _.extend({}, this, this.model.attributes);
},
setElement: function () {
var response = Handlebones.View.prototype.setElement.apply(this, arguments);
this.el.setAttribute(modelCidAttributeName, this.model.cid);
return response;
}
});
// CollectionView
function handleChangeFromEmptyToNotEmpty() {
this.emptyClassName && removeClassName.call(this.el, this.emptyClassName);
if (this._emptyViewInstance) {
this._emptyViewInstance.remove();
this.removeChild(this._emptyViewInstance);
}
replaceHTML.call(this, "");
}
function handleChangeFromNotEmptyToEmpty() {
this.emptyClassName && addClassName.call(this.el, this.emptyClassName);
replaceHTML.call(this, "");
if (this.emptyView) {
this._emptyViewInstance = new this.emptyView();
this.addChild(this._emptyViewInstance);
this._emptyViewInstance.appendTo(this.el);
}
}
function applyVisibilityFilter() {
if (this.modelFilter) {
this.collection.forEach(function (model) {
applyModelVisiblityFilter.call(this, model);
}, this);
}
}
function applyModelVisiblityFilter(model, el) {
if (this.modelFilter) {
if (!el) {
var selector = "[" + modelCidAttributeName + "=\"" + model.cid + "\"]";
el = this.$(selector)[0];
}
if (modelShouldBeVisible.call(this, model)) {
el.style.display = null;
} else {
el.style.display = "none";
}
}
}
function modelShouldBeVisible(model) {
return this.modelFilter(model, this.collection.indexOf(model));
}
Handlebones.CollectionView = Handlebones.View.extend({
modelView: Handlebones.ModelView,
emptyView: false,
emptyClassName: "empty",
modelFilter: false,
initialize: function () {
this.listenTo(this.collection, {
reset: this.render,
sort: this.render,
change: function (model) {
applyModelVisiblityFilter.call(this, model);
},
add: function (model) {
if (this.collection.length === 1) {
handleChangeFromEmptyToNotEmpty.call(this);
}
var index = this.collection.indexOf(model);
this.addModel(model, index);
},
remove: function (model) {
this.removeModel(model);
this.collection.length === 0 && handleChangeFromNotEmptyToEmpty.call(this);
}
});
},
render: function () {
if (this.collection.length === 0) {
handleChangeFromNotEmptyToEmpty.call(this);
} else {
handleChangeFromEmptyToNotEmpty.call(this);
this._useDocumentFragment(function () {
this.collection.forEach(function (model) {
this.addModel(model);
}, this);
});
}
++this._renderCount;
this.trigger("render");
return this;
},
addModel: function (model, index) {
var view;
view = new this.modelView({
model: model
});
this.addChild(view);
if (_.isUndefined(index)) {
view.appendTo(this.el);
} else {
var previousModel = index > 0 ? this.collection.at(index - 1) : false,
insertionPoint = this.el.firstChild;
if (previousModel) {
var selector = "[" + modelCidAttributeName + "=\"" + previousModel.cid + "\"]";
var nextEl = this.$(selector)[0];
if (nextEl) {
insertionPoint = nextEl.nextSibling;
}
}
view.appendTo(_.bind(function () {
this.el.insertBefore(view.el, insertionPoint);
}, this));
}
applyModelVisiblityFilter.call(this, model, view.el);
this.trigger("addModel", model, view);
return this;
},
removeModel: function (model) {
var selector = "[" + modelCidAttributeName + "=\"" + model.cid + "\"]",
el = this.$(selector)[0];
if (!el) {
return this;
}
var viewCid = el.getAttribute(viewCidAttributeName),
view = this.children[viewCid];
view.remove();
this.removeChild(view);
this.trigger("removeModel", model, view);
return this;
},
updateModelFilter: function () {
applyVisibilityFilter.call(this);
}
});
// Util
function deref(token, scope, encode) {
if (token.match(/^("|')/) && token.match(/("|')$/)) {
return token.replace(/(^("|')|('|")$)/g, "");
}
var segments = token.split("."),
len = segments.length;
for (var i = 0; scope && i < len; i++) {
if (segments[i] !== "this") {
scope = scope[segments[i]];
}
}
if (encode && _.isString(scope)) {
return encodeURIComponent(scope);
} else {
return scope;
}
}
Handlebones.Util = {
tag: function (attributes, content, scope) {
if (attributes.className) {
attributes["class"] = attributes.className;
delete attributes.className;
}
var htmlAttributes = _.omit(attributes, "tagName", "tag"),
tag = attributes.tag || attributes.tagName || "div",
space = _.keys(htmlAttributes).length > 0 ? " " : "";
return "<" + tag + space + _.map(htmlAttributes, function (value, key) {
var formattedValue = value;
if (scope) {
formattedValue = Handlebones.Util.expandToken(value, scope);
}
formattedValue = Handlebars.Utils.escapeExpression(formattedValue);
return key + "=\"" + formattedValue + "\"";
}).join(" ") + ">" + (_.isUndefined(content) ? "" : content) + "</" + tag + ">";
},
expandToken: function (input, scope, encode) {
if (input && input.indexOf && input.indexOf("{{") >= 0) {
var re = /(?:\{?[^{]+)|(?:\{\{([^}]+)\}\})/g,
match,
ret = [];
var mapper = function (param) {
return deref(param, scope, encode);
};
while (match = re.exec(input)) {
if (match[1]) {
var params = match[1].split(/\s+/);
if (params.length > 1) {
var helper = params.shift();
params = _.map(params, mapper);
if (Handlebars.helpers[helper]) {
ret.push(Handlebars.helpers[helper].apply(scope, params));
} else {
// If the helper is not defined do nothing
ret.push(match[0]);
}
} else {
ret.push(deref(params[0], scope, encode));
}
} else {
ret.push(match[0]);
}
}
input = ret.join("");
}
return input;
}
};
Handlebars.registerHelper("view", function (view) {
if (!view) {
return "";
}
var htmlAttributes = {
// ensure generated placeholder tag in template
// will match tag of view instance
tagName: view.el.tagName.toLowerCase()
};
htmlAttributes[viewPlaceholderAttributeName] = view.cid;
var output = Handlebones.Util.tag(htmlAttributes, "", this);
return new Handlebars.SafeString(output);
});
function appendChildViews() {
var placeholders = this.$("[" + viewPlaceholderAttributeName + "]");
_.each(placeholders, function (el) {
var placeholderId = el.getAttribute(viewPlaceholderAttributeName),
view = this.children[placeholderId];
if (view) {
ensureRendered.call(view);
el.parentNode.replaceChild(view.el, el);
}
}, this);
}
if (hasDOMLib) {
$.fn.view = function () {
var selector = "[" + viewCidAttributeName + "]",
el = $(this).closest(selector);
return (el && viewsIndexedByCid[el.attr(viewCidAttributeName)]) || false;
};
}
return Handlebones;
});