-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
view_support.js
830 lines (660 loc) · 24.4 KB
/
view_support.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
import { assert, deprecate } from 'ember-metal/debug';
import EmberError from 'ember-metal/error';
import { get } from 'ember-metal/property_get';
import run from 'ember-metal/run_loop';
import { addObserver, removeObserver } from 'ember-metal/observer';
import { guidFor } from 'ember-metal/utils';
import { computed } from 'ember-metal/computed';
import { Mixin } from 'ember-metal/mixin';
import { POST_INIT } from 'ember-runtime/system/core_object';
import isEnabled from 'ember-metal/features';
import { symbol } from 'ember-metal/utils';
import { getOwner } from 'container/owner';
const INIT_WAS_CALLED = symbol('INIT_WAS_CALLED');
import jQuery from 'ember-views/system/jquery';
function K() { return this; }
export default Mixin.create({
concatenatedProperties: ['attributeBindings'],
/**
@property isView
@type Boolean
@default true
@static
@private
*/
isView: true,
// ..........................................................
// TEMPLATE SUPPORT
//
/**
The name of the template to lookup if no template is provided.
By default `Ember.View` will lookup a template with this name in
`Ember.TEMPLATES` (a shared global object).
@property templateName
@type String
@default null
@private
*/
templateName: null,
/**
The name of the layout to lookup if no layout is provided.
By default `Ember.View` will lookup a template with this name in
`Ember.TEMPLATES` (a shared global object).
@property layoutName
@type String
@default null
@private
*/
layoutName: null,
/**
The template used to render the view. This should be a function that
accepts an optional context parameter and returns a string of HTML that
will be inserted into the DOM relative to its parent view.
In general, you should set the `templateName` property instead of setting
the template yourself.
@property template
@type Function
@private
*/
template: computed({
get() {
var templateName = get(this, 'templateName');
var template = this.templateForName(templateName, 'template');
assert('You specified the templateName ' + templateName + ' for ' + this + ', but it did not exist.', !templateName || !!template);
return template || get(this, 'defaultTemplate');
},
set(key, value) {
if (value !== undefined) { return value; }
return get(this, key);
}
}),
/**
A view may contain a layout. A layout is a regular template but
supersedes the `template` property during rendering. It is the
responsibility of the layout template to retrieve the `template`
property from the view (or alternatively, call `Handlebars.helpers.yield`,
`{{yield}}`) to render it in the correct location.
This is useful for a view that has a shared wrapper, but which delegates
the rendering of the contents of the wrapper to the `template` property
on a subclass.
@property layout
@type Function
@private
*/
layout: computed({
get(key) {
var layoutName = get(this, 'layoutName');
var layout = this.templateForName(layoutName, 'layout');
assert('You specified the layoutName ' + layoutName + ' for ' + this + ', but it did not exist.', !layoutName || !!layout);
return layout || get(this, 'defaultLayout');
},
set(key, value) {
return value;
}
}),
templateForName(name, type) {
if (!name) { return; }
assert('templateNames are not allowed to contain periods: ' + name, name.indexOf('.') === -1);
let owner = getOwner(this);
if (!owner) {
throw new EmberError('Container was not found when looking up a views template. ' +
'This is most likely due to manually instantiating an Ember.View. ' +
'See: http://git.io/EKPpnA');
}
return owner.lookup('template:' + name);
},
/**
Return the nearest ancestor that is an instance of the provided
class or mixin.
@method nearestOfType
@param {Class,Mixin} klass Subclass of Ember.View (or Ember.View itself),
or an instance of Ember.Mixin.
@return Ember.View
@private
*/
nearestOfType(klass) {
var view = get(this, 'parentView');
var isOfType = klass instanceof Mixin ?
function(view) { return klass.detect(view); } :
function(view) { return klass.detect(view.constructor); };
while (view) {
if (isOfType(view)) { return view; }
view = get(view, 'parentView');
}
},
/**
Return the nearest ancestor that has a given property.
@method nearestWithProperty
@param {String} property A property name
@return Ember.View
@private
*/
nearestWithProperty(property) {
var view = get(this, 'parentView');
while (view) {
if (property in view) { return view; }
view = get(view, 'parentView');
}
},
/**
Renders the view again. This will work regardless of whether the
view is already in the DOM or not. If the view is in the DOM, the
rendering process will be deferred to give bindings a chance
to synchronize.
If children were added during the rendering process using `appendChild`,
`rerender` will remove them, because they will be added again
if needed by the next `render`.
In general, if the display of your view changes, you should modify
the DOM element directly instead of manually calling `rerender`, which can
be slow.
@method rerender
@public
*/
rerender() {
return this._currentState.rerender(this);
},
// ..........................................................
// ELEMENT SUPPORT
//
/**
Returns the current DOM element for the view.
@property element
@type DOMElement
@public
*/
element: null,
/**
Returns a jQuery object for this view's element. If you pass in a selector
string, this method will return a jQuery object, using the current element
as its buffer.
For example, calling `view.$('li')` will return a jQuery object containing
all of the `li` elements inside the DOM element of this view.
@method $
@param {String} [selector] a jQuery-compatible selector string
@return {jQuery} the jQuery object for the DOM node
@public
*/
$(sel) {
assert('You cannot access this.$() on a component with `tagName: \'\'` specified.', this.tagName !== '');
return this._currentState.$(this, sel);
},
forEachChildView(callback) {
var childViews = this.childViews;
if (!childViews) { return this; }
var len = childViews.length;
var view, idx;
for (idx = 0; idx < len; idx++) {
view = childViews[idx];
callback(view);
}
return this;
},
/**
Appends the view's element to the specified parent element.
If the view does not have an HTML representation yet, `createElement()`
will be called automatically.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the given element until all bindings have
finished synchronizing.
This is not typically a function that you will need to call directly when
building your application. You might consider using `Ember.ContainerView`
instead. If you do need to use `appendTo`, be sure that the target element
you are providing is associated with an `Ember.Application` and does not
have an ancestor element that is associated with an Ember view.
@method appendTo
@param {String|DOMElement|jQuery} A selector, element, HTML string, or jQuery object
@return {Ember.View} receiver
@private
*/
appendTo(selector) {
if (isEnabled('ember-application-visit')) {
let $ = this._environment ? this._environment.options.jQuery : jQuery;
if ($) {
let target = $(selector);
assert('You tried to append to (' + selector + ') but that isn\'t in the DOM', target.length > 0);
assert('You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.', !target.is('.ember-view') && !target.parents().is('.ember-view'));
this.renderer.appendTo(this, target[0]);
} else {
let target = selector;
assert('You tried to append to a selector string (' + selector + ') in an environment without jQuery', typeof target !== 'string');
assert('You tried to append to a non-Element (' + selector + ') in an environment without jQuery', typeof selector.appendChild === 'function');
this.renderer.appendTo(this, target);
}
} else {
let target = jQuery(selector);
assert('You tried to append to (' + selector + ') but that isn\'t in the DOM', target.length > 0);
assert('You cannot append to an existing Ember.View. Consider using Ember.ContainerView instead.', !target.is('.ember-view') && !target.parents().is('.ember-view'));
this.renderer.appendTo(this, target[0]);
}
return this;
},
/**
@private
Creates a new DOM element, renders the view into it, then returns the
element.
By default, the element created and rendered into will be a `BODY` element,
since this is the default context that views are rendered into when being
inserted directly into the DOM.
```js
var element = view.renderToElement();
element.tagName; // => "BODY"
```
You can override the kind of element rendered into and returned by
specifying an optional tag name as the first argument.
```js
var element = view.renderToElement('table');
element.tagName; // => "TABLE"
```
This method is useful if you want to render the view into an element that
is not in the document's body. Instead, a new `body` element, detached from
the DOM is returned. FastBoot uses this to serialize the rendered view into
a string for transmission over the network.
```js
app.visit('/').then(function(instance) {
var element;
Ember.run(function() {
element = renderToElement(instance);
});
res.send(serialize(element));
});
```
@method renderToElement
@param {String} tagName The tag of the element to create and render into. Defaults to "body".
@return {HTMLBodyElement} element
@private
*/
renderToElement(tagName) {
tagName = tagName || 'body';
var element = this.renderer._dom.createElement(tagName);
this.renderer.appendTo(this, element);
return element;
},
/**
Replaces the content of the specified parent element with this view's
element. If the view does not have an HTML representation yet,
the element will be generated automatically.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the given element until all bindings have
finished synchronizing
@method replaceIn
@param {String|DOMElement|jQuery} target A selector, element, HTML string, or jQuery object
@return {Ember.View} received
@private
*/
replaceIn(selector) {
var target = jQuery(selector);
assert('You tried to replace in (' + selector + ') but that isn\'t in the DOM', target.length > 0);
assert('You cannot replace an existing Ember.View. Consider using Ember.ContainerView instead.', !target.is('.ember-view') && !target.parents().is('.ember-view'));
this.renderer.replaceIn(this, target[0]);
return this;
},
/**
Appends the view's element to the document body. If the view does
not have an HTML representation yet
the element will be generated automatically.
If your application uses the `rootElement` property, you must append
the view within that element. Rendering views outside of the `rootElement`
is not supported.
Note that this method just schedules the view to be appended; the DOM
element will not be appended to the document body until all bindings have
finished synchronizing.
@method append
@return {Ember.View} receiver
@private
*/
append() {
return this.appendTo(document.body);
},
/**
Removes the view's element from the element to which it is attached.
@method remove
@return {Ember.View} receiver
@private
*/
remove() {
// What we should really do here is wait until the end of the run loop
// to determine if the element has been re-appended to a different
// element.
// In the interim, we will just re-render if that happens. It is more
// important than elements get garbage collected.
if (!this.removedFromDOM) { this.destroyElement(); }
// Set flag to avoid future renders
this._willInsert = false;
},
/**
The HTML `id` of the view's element in the DOM. You can provide this
value yourself but it must be unique (just as in HTML):
```handlebars
{{my-component elementId="a-really-cool-id"}}
```
If not manually set a default value will be provided by the framework.
Once rendered an element's `elementId` is considered immutable and you
should never change it. If you need to compute a dynamic value for the
`elementId`, you should do this when the component or element is being
instantiated:
```javascript
export default Ember.Component.extend({
setElementId: Ember.on('init', function() {
var index = this.get('index');
this.set('elementId', 'component-id' + index);
})
});
```
@property elementId
@type String
@public
*/
elementId: null,
/**
Attempts to discover the element in the parent element. The default
implementation looks for an element with an ID of `elementId` (or the
view's guid if `elementId` is null). You can override this method to
provide your own form of lookup. For example, if you want to discover your
element using a CSS class name instead of an ID.
@method findElementInParentElement
@param {DOMElement} parentElement The parent's DOM element
@return {DOMElement} The discovered element
@private
*/
findElementInParentElement(parentElem) {
var id = '#' + this.elementId;
return jQuery(id)[0] || jQuery(id, parentElem)[0];
},
/**
Creates a DOM representation of the view and all of its child views by
recursively calling the `render()` method. Once the element is created,
it sets the `element` property of the view to the rendered element.
After the element has been inserted into the DOM, `didInsertElement` will
be called on this view and all of its child views.
@method createElement
@return {Ember.View} receiver
@private
*/
createElement() {
if (this.element) { return this; }
this.renderer.createElement(this);
return this;
},
/**
Called when a view is going to insert an element into the DOM.
@event willInsertElement
@public
*/
willInsertElement: K,
/**
Called when the element of the view has been inserted into the DOM
or after the view was re-rendered. Override this function to do any
set up that requires an element in the document body.
When a view has children, didInsertElement will be called on the
child view(s) first, bubbling upwards through the hierarchy.
@event didInsertElement
@public
*/
didInsertElement: K,
/**
Called when the view is about to rerender, but before anything has
been torn down. This is a good opportunity to tear down any manual
observers you have installed based on the DOM state
@event willClearRender
@public
*/
willClearRender: K,
/**
Destroys any existing element along with the element for any child views
as well. If the view does not currently have a element, then this method
will do nothing.
If you implement `willDestroyElement()` on your view, then this method will
be invoked on your view before your element is destroyed to give you a
chance to clean up any event handlers, etc.
If you write a `willDestroyElement()` handler, you can assume that your
`didInsertElement()` handler was called earlier for the same element.
You should not call or override this method yourself, but you may
want to implement the above callbacks.
@method destroyElement
@return {Ember.View} receiver
@private
*/
destroyElement() {
return this._currentState.destroyElement(this);
},
/**
Called when the element of the view is going to be destroyed. Override
this function to do any teardown that requires an element, like removing
event listeners.
Please note: any property changes made during this event will have no
effect on object observers.
@event willDestroyElement
@public
*/
willDestroyElement: K,
/**
Called when the parentView property has changed.
@event parentViewDidChange
@private
*/
parentViewDidChange: K,
// ..........................................................
// STANDARD RENDER PROPERTIES
//
/**
Tag name for the view's outer element. The tag name is only used when an
element is first created. If you change the `tagName` for an element, you
must destroy and recreate the view element.
By default, the render buffer will use a `<div>` tag for views.
@property tagName
@type String
@default null
@public
*/
// We leave this null by default so we can tell the difference between
// the default case and a user-specified tag.
tagName: null,
/*
Used to specify a default tagName that can be overridden when extending
or invoking from a template.
@property _defaultTagName
@private
*/
/**
Normally, Ember's component model is "write-only". The component takes a
bunch of attributes that it got passed in, and uses them to render its
template.
One nice thing about this model is that if you try to set a value to the
same thing as last time, Ember (through HTMLBars) will avoid doing any
work on the DOM.
This is not just a performance optimization. If an attribute has not
changed, it is important not to clobber the element's "hidden state".
For example, if you set an input's `value` to the same value as before,
it will clobber selection state and cursor position. In other words,
setting an attribute is not **always** idempotent.
This method provides a way to read an element's attribute and also
update the last value Ember knows about at the same time. This makes
setting an attribute idempotent.
In particular, what this means is that if you get an `<input>` element's
`value` attribute and then re-render the template with the same value,
it will avoid clobbering the cursor and selection position.
Since most attribute sets are idempotent in the browser, you typically
can get away with reading attributes using jQuery, but the most reliable
way to do so is through this method.
@method readDOMAttr
@param {String} name the name of the attribute
@return String
@public
*/
readDOMAttr(name) {
let attr = this._renderNode.childNodes.filter(node => node.attrName === name)[0];
if (!attr) { return null; }
return attr.getContent();
},
// .......................................................
// CORE DISPLAY METHODS
//
/**
Setup a view, but do not finish waking it up.
* configure `childViews`
* register the view with the global views hash, which is used for event
dispatch
@method init
@private
*/
init() {
this._super(...arguments);
if (!this.elementId) {
this.elementId = guidFor(this);
}
this.scheduledRevalidation = false;
this[INIT_WAS_CALLED] = true;
assert(
'Using a custom `.render` function is no longer supported.',
!this.render
);
},
/*
This is a special hook implemented in CoreObject, that allows Views/Components
to have a way to ensure that `init` fires before `didInitAttrs` / `didReceiveAttrs`
(so that `this._super` in init does not trigger `didReceiveAttrs` before the classes
own `init` is finished).
@method __postInitInitialization
@private
*/
[POST_INIT]: function() {
this._super(...arguments);
assert(
`You must call \`this._super(...arguments);\` when implementing \`init\` in a component. Please update ${this} to call \`this._super\` from \`init\`.`,
this[INIT_WAS_CALLED]
);
this.renderer.componentInitAttrs(this, this.attrs || {});
},
__defineNonEnumerable(property) {
this[property.name] = property.descriptor.value;
},
revalidate() {
this.renderer.revalidateTopLevelView(this);
this.scheduledRevalidation = false;
},
scheduleRevalidate(node, label, manualRerender) {
if (node && !this._dispatching && this.env.renderedNodes.has(node)) {
if (manualRerender) {
deprecate(
`You manually rerendered ${label} (a parent component) from a child component during the rendering process. This rarely worked in Ember 1.x and will be removed in Ember 3.0`,
false,
{ id: 'ember-views.manual-parent-rerender', until: '3.0.0' }
);
} else {
deprecate(
`You modified ${label} twice in a single render. This was unreliable in Ember 1.x and will be removed in Ember 3.0`,
false,
{ id: 'ember-views.render-double-modify', until: '3.0.0' }
);
}
run.scheduleOnce('render', this, this.revalidate);
return;
}
deprecate(
`A property of ${this} was modified inside the ${this._dispatching} hook. You should never change properties on components, services or models during ${this._dispatching} because it causes significant performance degradation.`,
!this._dispatching,
{ id: 'ember-views.dispatching-modify-property', until: '3.0.0' }
);
if (!this.scheduledRevalidation || this._dispatching) {
this.scheduledRevalidation = true;
run.scheduleOnce('render', this, this.revalidate);
}
},
templateRenderer: null,
/**
Removes the view from its `parentView`, if one is found. Otherwise
does nothing.
@method removeFromParent
@return {Ember.View} receiver
@private
*/
removeFromParent() {
var parent = this.parentView;
// Remove DOM element from parent
this.remove();
if (parent) { parent.removeChild(this); }
return this;
},
/**
You must call `destroy` on a view to destroy the view (and all of its
child views). This will remove the view from any parent node, then make
sure that the DOM element managed by the view can be released by the
memory manager.
@method destroy
@private
*/
destroy() {
// get parentView before calling super because it'll be destroyed
var parentView = this.parentView;
var viewName = this.viewName;
if (!this._super(...arguments)) { return; }
// remove from non-virtual parent view if viewName was specified
if (viewName && parentView) {
parentView.set(viewName, null);
}
// Destroy HTMLbars template
if (this.lastResult) {
this.lastResult.destroy();
}
return this;
},
// .......................................................
// EVENT HANDLING
//
/**
Handle events from `Ember.EventDispatcher`
@method handleEvent
@param eventName {String}
@param evt {Event}
@private
*/
handleEvent(eventName, evt) {
return this._currentState.handleEvent(this, eventName, evt);
},
/**
Registers the view in the view registry, keyed on the view's `elementId`.
This is used by the EventDispatcher to locate the view in response to
events.
This method should only be called once the view has been inserted into the
DOM.
@method _register
@private
*/
_register() {
assert('Attempted to register a view with an id already in use: ' + this.elementId, !this._viewRegistry[this.elementId]);
this._viewRegistry[this.elementId] = this;
},
/**
Removes the view from the view registry. This should be called when the
view is removed from DOM.
@method _unregister
@private
*/
_unregister() {
delete this._viewRegistry[this.elementId];
},
registerObserver(root, path, target, observer) {
if (!observer && 'function' === typeof target) {
observer = target;
target = null;
}
if (!root || typeof root !== 'object') {
return;
}
var scheduledObserver = this._wrapAsScheduled(observer);
addObserver(root, path, target, scheduledObserver);
this.one('willClearRender', function() {
removeObserver(root, path, target, scheduledObserver);
});
},
_wrapAsScheduled(fn) {
var view = this;
var stateCheckedFn = function() {
view._currentState.invokeObserver(this, fn);
};
var scheduledFn = function() {
run.scheduleOnce('render', this, stateCheckedFn);
};
return scheduledFn;
}
});