1
1
2
- import { assign } from './object' ;
3
-
2
+ import { assign } from '../utils/object' ;
4
3
/**
5
4
* Observe a DOM element changes, falls back to eventListener mode
6
5
* @param {Element } el The DOM element to observe
@@ -15,42 +14,14 @@ export default function observeDOM(el, callback, opts) {
15
14
if ( MutationObserver ) {
16
15
// Define a new observer
17
16
const obs = new MutationObserver ( mutations => {
18
- let changed = false ;
19
- // A Mutation can contain several changes, so we loop through them to see what has changed
20
- // We break out of the loop early if any "significant" change has been detected
21
- for ( let i = 0 ; i < mutations . length && ! changed ; i ++ ) {
22
- // The muttion record
23
- const mutation = mutations [ i ] ;
24
- // Mutation Type
25
- const type = mutation . type ;
26
- // DOM Node
27
- const target = mutation . target ;
28
- // Previous Value (only for characterData and attributes)
29
- const old = mutation . oldValue ;
30
- if ( type === 'characterData' && target . nodeType === Node . TEXT_NODE && old !== target . data ) {
31
- // We ignore nodes that are not TEXt (i.e. comments, etc) as they don't change layout
32
- // Updating character data with the same value still triggers a mutation
33
- // So we compare the old value to the new value
34
- changed = true ;
35
- } else if ( type === 'attributes' && target . getAttribute ( mutation . attributeName ) !== old ) {
36
- // Updating an attribute with the same value still triggers a mutation
37
- // So we compare the old value to the new value
38
- changed = true ;
39
- } else if ( type === 'childList' && ( mutation . addedNodes . length > 0 || mutation . removedNodes . length > 0 ) ) {
40
- // This includes HTMLElement and Text Nodes being added/removed
41
- changed = true ;
42
- }
43
- }
44
- if ( changed ) {
45
- // We only call the callback if a change that could affect layout/size truely happened.
17
+ if ( mutations [ 0 ] . addedNodes . length > 0 || mutations [ 0 ] . removedNodes . length > 0 ) {
46
18
callback ( ) ;
47
19
}
48
20
} ) ;
49
21
50
- // Have the observer observe foo for changes in children, etc
22
+ // Have the observer observe foo for changes in children
51
23
obs . observe ( el , assign ( { childList : true , subtree : true } , opts ) ) ;
52
24
} else if ( eventListenerSupported ) {
53
- // Legacy interface. most likely not used in modern browsers
54
25
el . addEventListener ( 'DOMNodeInserted' , callback , false ) ;
55
26
el . addEventListener ( 'DOMNodeRemoved' , callback , false ) ;
56
27
}
0 commit comments