Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using object wrappers to extend the JavaScripts DOM?

Tags:

javascript

I'm trying to add simple functions to the JavaScript DOM, e.g. an addClass function, I implemented this first with the following code:

Element.prototype.addClass = function(className) {
    this.className += ' ' + className;
}; 

However after much reading (http://perfectionkills.com/whats-wrong-with-extending-the-dom/ was good) it seems this is a terrible way to extend the DOM for a number of reasons.

The above article states:

One of the most common alternatives to this whole mess of DOM extension is object wrappers

Which is fine, apparently the general consensus is to use Object wrappers if you want to extend the DOM. The problem is I can't find any good examples anywhere on how you actually use object wrappers to extend the DOM ...

Can anybody give me an example of how to do so? Maybe using the above code?

like image 920
Sean Avatar asked Apr 29 '13 12:04

Sean


1 Answers

Object wrappers are more expensive than extensions because you need to create a new object, but they are safer.

A simple implementation that wraps only a single element could look like this:

(function() {
    window.wrap = function(el) {
        return new Wrapper(el);
    };

    function Wrapper(el) {
        this.element = el;
    }

    Wrapper.prototype.addClass = function(cls) {
        if (this.element)
            this.element.className += " " + cls;
    }
    Wrapper.prototype.swap = function(el) {
        this.element = el;
    }
})();

Then you could make a new wrapper, and to be more efficient, you could reuse it with various elements.

var wrp = wrap(document.body);

wrp.addClass("foo");
wrp.swap(document.body.firstElementChild);
wrp.addClass("bar");

Another feature you could implement would be to add return this; to all the wrapper methods. That way you could chain your function calls if you like.

var wrp = wrap(document.body);

wrp.addClass("foo")
   .swap(document.body.firstElementChild)
   .addClass("bar");

You could also implement your wrapper to hold multiple elements at numeric indices like an Array, or better, simply hold an Array of elements.

like image 149
2 revs, 2 users 99%user1106925 Avatar answered Sep 19 '22 01:09

2 revs, 2 users 99%user1106925