Skip to content

Instantly share code, notes, and snippets.

@sketchpunk
Created April 2, 2019 16:48
Show Gist options
  • Save sketchpunk/9e2a4dfe88b6daa34b92741522758e51 to your computer and use it in GitHub Desktop.
Save sketchpunk/9e2a4dfe88b6daa34b92741522758e51 to your computer and use it in GitHub Desktop.
MutationObserver
/** Using Mutation Observer, it checks to see if a Widget has been resized. */
class ResizeObserver{
constructor( elm, cb, timeOut=300 ){
this.callBack = cb;
this.timeOut = timeOut;
this.obs = new MutationObserver( this.onCallback.bind(this) );
this.obs.observe( elm, { attributes:true, childList:false, characterData:false, attributeOldValue:true } );
}
onCallback( mList, ob ){
// When Widget finalizes the resize, it does about 7 style modifications.
// But when its resizing on mouse move, it does a constant 1 or 2 style modifications.
// So by checking if the change is less then 3, we can kind of guarantee that
// the final resize happens when there is more then 2 updates to style.
if( mList.length < 3 ) return;
let m;
for( m of mList ){
if( m.attributeName !== "style" || !m.oldValue || m.oldValue.indexOf("width") == -1 ) continue;
setTimeout( this.callBack, this.timeOut ); // Widget's animate their resize. So won't know the full resize till some time later.
return;
}
}
dispose(){
this.obs.disconnect();
delete this.obs;
delete this.callback;
}
}
//#########################################################################################
//window.ResizeObserver = ResizeObserver; //Make it available at the global scope for non module javascript
export default ResizeObserver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment