Skip to content

better dom 2: a new beginning

Rogier Spieker edited this page Apr 22, 2015 · 3 revisions

From the start I wanted to create a lightweight and fast DOM library with extra features. Almost every core idea - live extensions, animations, event model etc. - was designed to be simple and unobtrusive. It's a bad approach to prohibit usage of any alternative library or framework on demand. Although better to avoid it of course: code size matters.

Changes that are made in the 2nd version are going to move forward in the direction of compatibility. The changes will require some adaptation for sure but in result code will be easier to understand for anybody who is not familiar with better-dom APIs yet.

Real arrays instead of array-like objects

I like standards and tried to add standards-based functional methods into the prototype of object that representes collection of $Elements. Having support for such array-like objects allow to simplify modifications for set of nodes:

links.on("click", function() {
  // handle click event
});

On the other hand DOM element usually have methods that quite difficult to apply on a collection: offset(), next[All] etc. jQuery for instance in such cases just invokes the action on the first element in the collection if it exists. And in better-dom version 1 I tried to do a similar thing... But to be honest it makes element wrapper interfaces to be more complicated and confusing.

Another problem is conflicting method names. I like to follow standards but in case of array-like objects it's not possible. For instance there are Node#contains and Array#contains that despite on the same name do a very completely different things.

Last arguments against array-like objects are a code size, maintance and separation of responsibilities. I want better-dom to be a minimalistic library for the DOM. Therefore goals like simplifying modification of set of elements, standards-based Array methods should be out of scope. They could be solved by existing libraries like underscore, lodash etc.

As a result better-dom version 2 does NOT have array-like objects anymore. Every method that might return set of elements now has a *All equivalent that returns a true array.

var links = DOM.createAll("a*3");

links.forEach(function(link) { 
  link.on("click", function() {
    // handle click event
  });
});

console.log(typeof links.indexOf); // => "function"
console.log(typeof links.push);    // => "function"
console.log(Array.isArray(links)); // => true

Such approach allows to use any existing utility library on large projects, and build-in methods on small ones. Also you can modify element arrays on demand.