This repository has been archived by the owner on Mar 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 129
/
thorax.js
274 lines (240 loc) · 7.38 KB
/
thorax.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
/*global cloneInheritVars, createInheritVars, createRegistryWrapper, getValue, inheritVars */
//support zepto.forEach on jQuery
if (!$.fn.forEach) {
$.fn.forEach = function(iterator, context) {
$.fn.each.call(this, function(index) {
iterator.call(context || this, this, index);
});
};
}
var viewNameAttributeName = 'data-view-name',
viewCidAttributeName = 'data-view-cid',
viewHelperAttributeName = 'data-view-helper';
//view instances
var viewsIndexedByCid = {};
var Thorax = this.Thorax = {
VERSION: '{{version}}',
templatePathPrefix: '',
templates: {},
//view classes
Views: {},
//certain error prone pieces of code (on Android only it seems)
//are wrapped in a try catch block, then trigger this handler in
//the catch, with the name of the function or event that was
//trying to be executed. Override this with a custom handler
//to debug / log / etc
onException: function(name, err) {
throw err;
}
};
Thorax.View = Backbone.View.extend({
constructor: function() {
var response = Backbone.View.apply(this, arguments);
_.each(inheritVars, function(obj) {
if (obj.ctor) {
obj.ctor.call(this, response);
}
}, this);
return response;
},
_configure: function(options) {
var self = this;
this._objectOptionsByCid = {};
this._boundDataObjectsByCid = {};
// Setup object event tracking
_.each(inheritVars, function(obj) {
self[obj.name] = [];
});
viewsIndexedByCid[this.cid] = this;
this.children = {};
this._renderCount = 0;
//this.options is removed in Thorax.View, we merge passed
//properties directly with the view and template context
_.extend(this, options || {});
// Setup helpers
bindHelpers.call(this);
//compile a string if it is set as this.template
if (typeof this.template === 'string') {
this.template = Handlebars.compile(this.template, {data: true});
} else if (this.name && !this.template) {
//fetch the template
this.template = Thorax.Util.getTemplate(this.name, true);
}
_.each(inheritVars, function(obj) {
if (obj.configure) {
obj.configure.call(this);
}
}, this);
},
setElement : function() {
var response = Backbone.View.prototype.setElement.apply(this, arguments);
this.name && this.$el.attr(viewNameAttributeName, this.name);
this.$el.attr(viewCidAttributeName, this.cid);
return response;
},
_addChild: function(view) {
this.children[view.cid] = view;
if (!view.parent) {
view.parent = this;
}
this.trigger('child', view);
return view;
},
destroy: function(options) {
options = _.defaults(options || {}, {
children: true
});
this.trigger('destroyed');
delete viewsIndexedByCid[this.cid];
if (options.children) {
_.each(this.children, function(child) {
child.parent = null;
child.destroy();
});
this.children = {};
}
this.freeze && this.freeze();
},
render: function(output) {
if (typeof output === 'undefined' || (!_.isElement(output) && !Thorax.Util.is$(output) && !(output && output.el) && typeof output !== 'string' && typeof output !== 'function')) {
if (!this.template) {
//if the name was set after the view was created try one more time to fetch a template
if (this.name) {
this.template = Thorax.Util.getTemplate(this.name, true);
}
if (!this.template) {
throw new Error('View ' + (this.name || this.cid) + '.render() was called with no content and no template set on the view.');
}
}
output = this.renderTemplate(this.template);
} else if (typeof output === 'function') {
output = this.renderTemplate(output);
}
//accept a view, string, Handlebars.SafeString or DOM element
this.html((output && output.el) || (output && output.string) || output);
++this._renderCount;
this.trigger('rendered');
return output;
},
context: function() {
if (this.model && this.model.attributes) {
return _.extend({}, this, (this.model && this.model.attributes) || {});
} else {
return this;
}
},
_getContext: function(attributes) {
return _.extend({}, getValue(this, 'context'), attributes || {});
},
// Private variables in handlebars / options.data in template helpers
_getData: function(data) {
return {
view: this,
cid: _.uniqueId('t'),
yield: function() {
// fn is seeded by template helper passing context to data
return data.fn && data.fn(data);
}
};
},
_getHelpers: function() {
if (this.helpers) {
return _.extend({}, Handlebars.helpers, this.helpers);
} else {
return Handlebars.helpers;
}
},
renderTemplate: function(file, data, ignoreErrors) {
var template;
data = this._getContext(data);
if (typeof file === 'function') {
template = file;
} else {
template = Thorax.Util.getTemplate(file);
}
if (!template) {
if (ignoreErrors) {
return '';
} else {
throw new Error('Unable to find template ' + file);
}
} else {
return template(data, {
helpers: this._getHelpers(),
data: this._getData(data)
});
}
},
ensureRendered: function() {
!this._renderCount && this.render();
},
appendTo: function(el) {
this.ensureRendered();
$(el).append(this.el);
this.trigger('ready');
},
html: function(html) {
if (typeof html === 'undefined') {
return this.el.innerHTML;
} else {
this.el.innerHTML = "";
var element;
if (this.collection && this._objectOptionsByCid[this.collection.cid] && this._renderCount) {
// preserveCollectionElement calls the callback after it has a reference
// to the collection element, calls the callback, then re-appends the element
preserveCollectionElement.call(this, function() {
element = this.$el.append(html);
});
} else {
element = this.$el.append(html);
}
this.trigger('append');
return element;
}
},
_anchorClick: function(event) {
var target = $(event.currentTarget),
href = target.attr('href');
// Route anything that starts with # or / (excluding //domain urls)
if (href && (href[0] === '#' || (href[0] === '/' && href[1] !== '/'))) {
Backbone.history.navigate(href, {
trigger: true
});
return false;
}
return true;
}
});
Thorax.View.extend = function() {
createInheritVars(this);
var child = Backbone.View.extend.apply(this, arguments);
child.__parent__ = this;
resetInheritVars(child);
return child;
};
createRegistryWrapper(Thorax.View, Thorax.Views);
function bindHelpers() {
if (this.helpers) {
_.each(this.helpers, function(helper, name) {
var view = this;
this.helpers[name] = function() {
var args = _.toArray(arguments),
options = _.last(args);
options.context = this;
return helper.apply(view, args);
};
}, this);
}
}
//$(selector).view() helper
$.fn.view = function(options) {
options = _.defaults(options || {}, {
helper: true
});
var selector = '[' + viewCidAttributeName + ']';
if (!options.helper) {
selector += ':not([' + viewHelperAttributeName + '])';
}
var el = $(this).closest(selector);
return (el && viewsIndexedByCid[el.attr(viewCidAttributeName)]) || false;
};