HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Simple DOM mutation abstraction

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mutationsimpledomabstraction

Problem

Background: I need to use mutation observers to watch for nodes being added/removed under a specific element.

The code below is an attempt to implement something re-usable that uses MutationObservers where available and falls back to mutation events where not available, providing a simple unified interface to both. The aim is to have the behaviour as predictable as possible regardless if the mechanism that is powering it behind.

You will notice it only implements a very part of the functionality that is available through these methods, but that is intentional, as it only implements the parts I need to use. I may look to extend it in the future.

```
/jslint plusplus: true, white: true, browser: true /

/*
* DOMChildListMutationListenerFactory definition
*/
function DOMChildListMutationListenerFactory() {'use strict';}

DOMChildListMutationListenerFactory.prototype.MOFactory = {
isSupported: function() {
// Determines whether the environment supports MutationObservers and caches a
// reference to the constructor if it does
'use strict';
if (this.MOConstructor === undefined) {
this.MOConstructor = null;
if (window.MutationObserver !== undefined) { // Mozilla/standard
this.MOConstructor = window.MutationObserver;
} else if (window.WebKitMutationObserver !== undefined) { // Webkit
this.MOConstructor = window.WebKitMutationObserver;
}
}
return this.MOConstructor !== null;
},
getObserver: function(callback) {
// Gets a MutationObserver instance
'use strict';
return new this.MOConstructor(callback);
}
};

DOMChildListMutationListenerFactory.prototype.getListener = function(element) {
// Determines which wrapper constructor to use, caches the result and gets an instance
'use strict';
if (this.WrapperInUse === undefined) {
DOMChildListMutationListenerFactory.prototype.WrapperInUse = null;
if (this.MOFactory.isSupported()) {
DOMChildListMutationListenerFactory.proto

Solution

2 observations:

-
You can place 'use strict' in an IIFE, which keeps lint happy and it's DRYer

function DOMChildListMutationListenerFactory() {'use strict';}

(function () 
{
  'use strict';
   /* Do your thing with DOMChildListMutationListenerFactory.prototype,
       no need to repeat 'use strict */
}();


-
You can assign all functions to a prototype with Object Literal Notation like you do for MOFactory. So you do not need to repeat over a dozen times
DOMChildListMutationListenerFactory.prototype.

Code Snippets

function DOMChildListMutationListenerFactory() {'use strict';}

(function () 
{
  'use strict';
   /* Do your thing with DOMChildListMutationListenerFactory.prototype,
       no need to repeat 'use strict */
}();

Context

StackExchange Code Review Q#18269, answer score: 2

Revisions (0)

No revisions yet.