At JSConf this year the question was asked, "what would you do if you had to re-write jQuery, today!". Well it just so happens that I am writing a book about the DOM in which I wanted to take the backbone out of jQuery (chaining & implicit looping) and re-write a modest amount of it for modern browsers. To be clear my motive for doing this is to help the readers of my book grok modern DOM programming. I am not intending rum.js to be released for use in production. Nor am trying to throw my code in the library ring. I'm simply trying to focus on the core pattern (chaining/implicit loop) used by jQuery that everyone has come to love and use. And to be honest. Its my opinion this pattern is the defacto pattern for working with the DOM (i.e. rum().method().method()).
So today I spent sometime thinking about what that backbone would look like. The code below is what I conjured up slamming some code together in a small matter of time (Warning: code is not for actual use). Check it out on jsfiddle.
var rum = function(selector){ return new rum.fn.init(selector); }; rum.fn = rum.prototype = { constructor:rum, init:function(selector){ var nodes = document.querySelectorAll(selector); for (var i = 0; i < nodes.length; i++) { this[i] = nodes[i]; } this.length = nodes.length; return this; }, rum:'0.1', addClass:function(classString){ this.each(function(){ this.classList.add(classString); }); return this; }, each:function(callback){ return rum.each(this, callback); } }; rum.each = function(object, callback){ var name; for (name in object) { if (callback.call( object[ name ], name, object[ name ] ) === false){ break; } } return object; }; rum.fn.init.prototype = rum.fn; //ok use rum like one uses jQuery rum('li').addClass('foo');