What is the best way to create library agnostic wrapper for JS library selectors? I have a custom JS framework, that aims to be as library-agnostic as possible. The problem I have is that for example Mootools enhances the returned DOM element with it’s own specific methods (inject, adopt etc.), and I don’t want these to be visible to the modules, layered on top of the framework (as Nicholas Zakas once described), to prevent misuses/accidents.
As a simple first-aid I created a custom selector that uses Mootools, it then creates custom Element -object/wrapper and hands selected (and enhanced) Mootools DOM element to it, thus the Mootools enhanced methods are not directly visible to the modules above. The problem with this approach is that I lose all the native functionality of the DOM element (value, style etc.) if it’s not specifically coded to the wrapper (Element).
Is there another and/or better way to do this? Something that would extend the native DOM element, thus providing the native properties/methods automatically AND offering advanced functionality through the wrapper (via Mootools, jQuery, whatnot…).
Some example code, how it’s currently done:
/*
* Wrap the native library element
*/
Element = function(_libElement) {
// Store native object
var libElement = _libElement;
return {
addClass: function(_class) { libElement.addClass(_class); return this; },
removeClass: function(_class) { libElement.removeClass(_class); return this; },
hasClass: function(_class) { return libElement.hasClass(_class); }
};
};
/*
* Custom selector
*/
getElement = function(_query) {
var elements = $$(_query);
// Wrap each element to Element wrapper
var num = elements.length;
while(num--) {
elements[num] = new Element(elements[num]);
}
return elements;
};
My approach would be to not worry about it, just pass back the native DOM element. If someone wants to rely on MooTools’ (or Prototype’s) enhancements to that DOM element, it’s their own lookout. In fact, if you try to prevent those enhancements showing through, I’d say you’re no longer being library-agnostic — instead, you’re being actively discriminatory (for lack of a better word!) against libraries that do native element enhancement. 🙂 Someone using those libraries presumably wants those enhancements.
If someone is building modules on top of your library, they should be aware of the environment on which they’re building (which doesn’t guarantee that those enhancements exist).
Somewhat off-topic, but it’s probably worth noting that extending DOM elements directly seems to be going out of fashion. I know that the Prototype guys are actively planning to use wrappers (a’la jQuery) instead in the fullness of time.