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

DOM override app

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

Problem

I'm building a mini-app that will display when changes to the DOM have been made by JavaScript. I have all of the functions that I can think of listed in the code. Is there a way to consolidate the functions into one, and have the overrides still function correctly?

var DomChanges = (function() {

  var a = Element.prototype.appendChild
  , b = Element.prototype.removeChild
  , c = Element.prototype.insertBefore
  , d = Element.prototype.insertAfter
  , e = Element.prototype.insertAttribute
  , f = Element.prototype.removeAttribute
  , g = Element.prototype.replaceChild
  , h = Element.prototype.createElement;

  Element.prototype.appendChild = function(){
    DomChange('appendChild', arguments);
    a.apply(this, arguments);
  };

  Element.prototype.removeChild = function() {
    DomChange('removeChild', arguments);
    b.apply(this, arguments);
  };

  Element.prototype.insertBefore = function() {
    DomChange('insertBefore', arguments);
    c.apply(this, arguments);
  };

  Element.prototype.insertAfter = function() {
    DomChange('insertAfter', arguments);
    d.apply(this, arguments);
  };

  Element.prototype.insertAttribute = function() {
    DomChange('insertAttribute', arguments);
    e.apply(this, arguments);
  };

  Element.prototype.removeAttribute = function() {
    DomChange('removeAttribute', arguments);
    f.apply(this, arguments);
  };

  Element.prototype.replaceChild = function() {
    DomChange('replaceChild', arguments);
    g.apply(this, arguments);
  };

  Element.prototype.createElement = function() {
    DomChange('createElement', arguments);
    h.apply(this, arguments);
  };

  function DomChange (ftype, arguments) {
    console.log('Dom has been changed');
  };

}());

Solution

//
// maybe this:
//
"appendChild removeChild insertBefore insertAfter insertAttribute removeAttribute replaceChild createElement"
.split(" ")
.forEach(
    function ( ftype ) {
        var corefn = this[ftype]
        this[ftype] = function () {
            DomChange( ftype, arguments );
            return corefn.apply( this, arguments );
        };
    },
    Element.prototype
);
//
//  do you overide .innerHTML somehow?
//

Code Snippets

//
// maybe this:
//
"appendChild removeChild insertBefore insertAfter insertAttribute removeAttribute replaceChild createElement"
.split(" ")
.forEach(
    function ( ftype ) {
        var corefn = this[ftype]
        this[ftype] = function () {
            DomChange( ftype, arguments );
            return corefn.apply( this, arguments );
        };
    },
    Element.prototype
);
//
//  do you overide .innerHTML somehow?
//

Context

StackExchange Code Review Q#31336, answer score: 3

Revisions (0)

No revisions yet.