-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
ext.js
534 lines (430 loc) · 15.7 KB
/
ext.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
534
require('ember-handlebars-compiler');
var slice = Array.prototype.slice,
originalTemplate = Ember.Handlebars.template;
/**
If a path starts with a reserved keyword, returns the root
that should be used.
@private
@method normalizePath
@for Ember
@param root {Object}
@param path {String}
@param data {Hash}
*/
var normalizePath = Ember.Handlebars.normalizePath = function(root, path, data) {
var keywords = (data && data.keywords) || {},
keyword, isKeyword;
// Get the first segment of the path. For example, if the
// path is "foo.bar.baz", returns "foo".
keyword = path.split('.', 1)[0];
// Test to see if the first path is a keyword that has been
// passed along in the view's data hash. If so, we will treat
// that object as the new root.
if (keywords.hasOwnProperty(keyword)) {
// Look up the value in the template's data hash.
root = keywords[keyword];
isKeyword = true;
// Handle cases where the entire path is the reserved
// word. In that case, return the object itself.
if (path === keyword) {
path = '';
} else {
// Strip the keyword from the path and look up
// the remainder from the newly found root.
path = path.substr(keyword.length+1);
}
}
return { root: root, path: path, isKeyword: isKeyword };
};
/**
Lookup both on root and on window. If the path starts with
a keyword, the corresponding object will be looked up in the
template's data hash and used to resolve the path.
@method get
@for Ember.Handlebars
@param {Object} root The object to look up the property on
@param {String} path The path to be lookedup
@param {Object} options The template's option hash
*/
var handlebarsGet = Ember.Handlebars.get = function(root, path, options) {
var data = options && options.data,
normalizedPath = normalizePath(root, path, data),
value;
if (Ember.FEATURES.isEnabled("ember-handlebars-caps-lookup")) {
// If the path starts with a capital letter, look it up on Ember.lookup,
// which defaults to the `window` object in browsers.
if (Ember.isGlobalPath(path)) {
value = Ember.get(Ember.lookup, path);
} else {
// In cases where the path begins with a keyword, change the
// root to the value represented by that keyword, and ensure
// the path is relative to it.
value = Ember.get(normalizedPath.root, normalizedPath.path);
}
} else {
root = normalizedPath.root;
path = normalizedPath.path;
value = Ember.get(root, path);
if (value === undefined && root !== Ember.lookup && Ember.isGlobalPath(path)) {
value = Ember.get(Ember.lookup, path);
}
}
return value;
};
/**
This method uses `Ember.Handlebars.get` to lookup a value, then ensures
that the value is escaped properly.
If `unescaped` is a truthy value then the escaping will not be performed.
@method getEscaped
@for Ember.Handlebars
@param {Object} root The object to look up the property on
@param {String} path The path to be lookedup
@param {Object} options The template's option hash
*/
Ember.Handlebars.getEscaped = function(root, path, options) {
var result = handlebarsGet(root, path, options);
if (result === null || result === undefined) {
result = "";
} else if (!(result instanceof Handlebars.SafeString)) {
result = String(result);
}
if (!options.hash.unescaped){
result = Handlebars.Utils.escapeExpression(result);
}
return result;
};
Ember.Handlebars.resolveParams = function(context, params, options) {
var resolvedParams = [], types = options.types, param, type;
for (var i=0, l=params.length; i<l; i++) {
param = params[i];
type = types[i];
if (type === 'ID') {
resolvedParams.push(handlebarsGet(context, param, options));
} else {
resolvedParams.push(param);
}
}
return resolvedParams;
};
Ember.Handlebars.resolveHash = function(context, hash, options) {
var resolvedHash = {}, types = options.hashTypes, type;
for (var key in hash) {
if (!hash.hasOwnProperty(key)) { continue; }
type = types[key];
if (type === 'ID') {
resolvedHash[key] = handlebarsGet(context, hash[key], options);
} else {
resolvedHash[key] = hash[key];
}
}
return resolvedHash;
};
/**
Registers a helper in Handlebars that will be called if no property with the
given name can be found on the current context object, and no helper with
that name is registered.
This throws an exception with a more helpful error message so the user can
track down where the problem is happening.
@private
@method helperMissing
@for Ember.Handlebars.helpers
@param {String} path
@param {Hash} options
*/
Ember.Handlebars.registerHelper('helperMissing', function(path) {
var error, view = "";
var options = arguments[arguments.length - 1];
var helper = Ember.Handlebars.resolveHelper(options.data.view.container, path);
if (helper) {
return helper.apply(this, slice.call(arguments, 1));
}
error = "%@ Handlebars error: Could not find property '%@' on object %@.";
if (options.data) {
view = options.data.view;
}
throw new Ember.Error(Ember.String.fmt(error, [view, path, this]));
});
/**
Registers a helper in Handlebars that will be called if no property with the
given name can be found on the current context object, and no helper with
that name is registered.
This throws an exception with a more helpful error message so the user can
track down where the problem is happening.
@private
@method helperMissing
@for Ember.Handlebars.helpers
@param {String} path
@param {Hash} options
*/
Ember.Handlebars.registerHelper('blockHelperMissing', function(path) {
var options = arguments[arguments.length - 1];
Ember.assert("`blockHelperMissing` was invoked without a helper name, which " +
"is most likely due to a mismatch between the version of " +
"Ember.js you're running now and the one used to precompile your " +
"templates. Please make sure the version of " +
"`ember-handlebars-compiler` you're using is up to date.", path);
var helper = Ember.Handlebars.resolveHelper(options.data.view.container, path);
if (helper) {
return helper.apply(this, slice.call(arguments, 1));
} else {
return Handlebars.helpers.helperMissing.call(this, path);
}
return Handlebars.helpers.blockHelperMissing.apply(this, arguments);
});
/**
Register a bound handlebars helper. Bound helpers behave similarly to regular
handlebars helpers, with the added ability to re-render when the underlying data
changes.
## Simple example
```javascript
Ember.Handlebars.registerBoundHelper('capitalize', function(value) {
return value.toUpperCase();
});
```
The above bound helper can be used inside of templates as follows:
```handlebars
{{capitalize name}}
```
In this case, when the `name` property of the template's context changes,
the rendered value of the helper will update to reflect this change.
## Example with options
Like normal handlebars helpers, bound helpers have access to the options
passed into the helper call.
```javascript
Ember.Handlebars.registerBoundHelper('repeat', function(value, options) {
var count = options.hash.count;
var a = [];
while(a.length < count) {
a.push(value);
}
return a.join('');
});
```
This helper could be used in a template as follows:
```handlebars
{{repeat text count=3}}
```
## Example with bound options
Bound hash options are also supported. Example:
```handlebars
{{repeat text countBinding="numRepeats"}}
```
In this example, count will be bound to the value of
the `numRepeats` property on the context. If that property
changes, the helper will be re-rendered.
## Example with extra dependencies
The `Ember.Handlebars.registerBoundHelper` method takes a variable length
third parameter which indicates extra dependencies on the passed in value.
This allows the handlebars helper to update when these dependencies change.
```javascript
Ember.Handlebars.registerBoundHelper('capitalizeName', function(value) {
return value.get('name').toUpperCase();
}, 'name');
```
## Example with multiple bound properties
`Ember.Handlebars.registerBoundHelper` supports binding to
multiple properties, e.g.:
```javascript
Ember.Handlebars.registerBoundHelper('concatenate', function() {
var values = Array.prototype.slice.call(arguments, 0, -1);
return values.join('||');
});
```
Which allows for template syntax such as `{{concatenate prop1 prop2}}` or
`{{concatenate prop1 prop2 prop3}}`. If any of the properties change,
the helpr will re-render. Note that dependency keys cannot be
using in conjunction with multi-property helpers, since it is ambiguous
which property the dependent keys would belong to.
## Use with unbound helper
The `{{unbound}}` helper can be used with bound helper invocations
to render them in their unbound form, e.g.
```handlebars
{{unbound capitalize name}}
```
In this example, if the name property changes, the helper
will not re-render.
## Use with blocks not supported
Bound helpers do not support use with Handlebars blocks or
the addition of child views of any kind.
@method registerBoundHelper
@for Ember.Handlebars
@param {String} name
@param {Function} function
@param {String} dependentKeys*
*/
Ember.Handlebars.registerBoundHelper = function(name, fn) {
var boundHelperArgs = slice.call(arguments, 1),
boundFn = Ember.Handlebars.makeBoundHelper.apply(this, boundHelperArgs);
Ember.Handlebars.registerHelper(name, boundFn);
};
/**
A (mostly) private helper function to `registerBoundHelper`. Takes the
provided Handlebars helper function fn and returns it in wrapped
bound helper form.
The main use case for using this outside of `registerBoundHelper`
is for registering helpers on the container:
```js
var boundHelperFn = Ember.Handlebars.makeBoundHelper(function(word) {
return word.toUpperCase();
});
container.register('helper:my-bound-helper', boundHelperFn);
```
In the above example, if the helper function hadn't been wrapped in
`makeBoundHelper`, the registered helper would be unbound.
@private
@method makeBoundHelper
@for Ember.Handlebars
@param {Function} function
@param {String} dependentKeys*
*/
Ember.Handlebars.makeBoundHelper = function(fn) {
var dependentKeys = slice.call(arguments, 1);
function helper() {
var properties = slice.call(arguments, 0, -1),
numProperties = properties.length,
options = arguments[arguments.length - 1],
normalizedProperties = [],
data = options.data,
types = data.isUnbound ? slice.call(options.types, 1) : options.types,
hash = options.hash,
view = data.view,
contexts = options.contexts,
currentContext = (contexts && contexts.length) ? contexts[0] : this,
prefixPathForDependentKeys = '',
loc, len, hashOption,
boundOption, property,
normalizedValue = Ember._SimpleHandlebarsView.prototype.normalizedValue;
Ember.assert("registerBoundHelper-generated helpers do not support use with Handlebars blocks.", !options.fn);
// Detect bound options (e.g. countBinding="otherCount")
var boundOptions = hash.boundOptions = {};
for (hashOption in hash) {
if (Ember.IS_BINDING.test(hashOption)) {
// Lop off 'Binding' suffix.
boundOptions[hashOption.slice(0, -7)] = hash[hashOption];
}
}
// Expose property names on data.properties object.
var watchedProperties = [];
data.properties = [];
for (loc = 0; loc < numProperties; ++loc) {
data.properties.push(properties[loc]);
if (types[loc] === 'ID') {
var normalizedProp = normalizePath(currentContext, properties[loc], data);
normalizedProperties.push(normalizedProp);
watchedProperties.push(normalizedProp);
} else {
if(data.isUnbound) {
normalizedProperties.push({path: properties[loc]});
}else {
normalizedProperties.push(null);
}
}
}
// Handle case when helper invocation is preceded by `unbound`, e.g.
// {{unbound myHelper foo}}
if (data.isUnbound) {
return evaluateUnboundHelper(this, fn, normalizedProperties, options);
}
var bindView = new Ember._SimpleHandlebarsView(null, null, !options.hash.unescaped, options.data);
// Override SimpleHandlebarsView's method for generating the view's content.
bindView.normalizedValue = function() {
var args = [], boundOption;
// Copy over bound hash options.
for (boundOption in boundOptions) {
if (!boundOptions.hasOwnProperty(boundOption)) { continue; }
property = normalizePath(currentContext, boundOptions[boundOption], data);
bindView.path = property.path;
bindView.pathRoot = property.root;
hash[boundOption] = normalizedValue.call(bindView);
}
for (loc = 0; loc < numProperties; ++loc) {
property = normalizedProperties[loc];
if (property) {
bindView.path = property.path;
bindView.pathRoot = property.root;
args.push(normalizedValue.call(bindView));
} else {
args.push(properties[loc]);
}
}
args.push(options);
// Run the supplied helper function.
return fn.apply(currentContext, args);
};
view.appendChild(bindView);
// Assemble list of watched properties that'll re-render this helper.
for (boundOption in boundOptions) {
if (boundOptions.hasOwnProperty(boundOption)) {
watchedProperties.push(normalizePath(currentContext, boundOptions[boundOption], data));
}
}
// Observe each property.
for (loc = 0, len = watchedProperties.length; loc < len; ++loc) {
property = watchedProperties[loc];
view.registerObserver(property.root, property.path, bindView, bindView.rerender);
}
if (types[0] !== 'ID' || normalizedProperties.length === 0) {
return;
}
// Add dependent key observers to the first param
var normalized = normalizedProperties[0],
pathRoot = normalized.root,
path = normalized.path;
if(!Ember.isEmpty(path)) {
prefixPathForDependentKeys = path + '.';
}
for (var i=0, l=dependentKeys.length; i<l; i++) {
view.registerObserver(pathRoot, prefixPathForDependentKeys + dependentKeys[i], bindView, bindView.rerender);
}
}
helper._rawFunction = fn;
return helper;
};
/**
Renders the unbound form of an otherwise bound helper function.
@private
@method evaluateUnboundHelper
@param {Function} fn
@param {Object} context
@param {Array} normalizedProperties
@param {String} options
*/
function evaluateUnboundHelper(context, fn, normalizedProperties, options) {
var args = [],
hash = options.hash,
boundOptions = hash.boundOptions,
types = slice.call(options.types, 1),
loc,
len,
property,
propertyType,
boundOption;
for (boundOption in boundOptions) {
if (!boundOptions.hasOwnProperty(boundOption)) { continue; }
hash[boundOption] = Ember.Handlebars.get(context, boundOptions[boundOption], options);
}
for(loc = 0, len = normalizedProperties.length; loc < len; ++loc) {
property = normalizedProperties[loc];
propertyType = types[loc];
if(propertyType === "ID") {
args.push(Ember.Handlebars.get(property.root, property.path, options));
} else {
args.push(property.path);
}
}
args.push(options);
return fn.apply(context, args);
}
/**
Overrides Handlebars.template so that we can distinguish
user-created, top-level templates from inner contexts.
@private
@method template
@for Ember.Handlebars
@param {String} spec
*/
Ember.Handlebars.template = function(spec) {
var t = originalTemplate(spec);
t.isTop = true;
return t;
};