My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, December 24, 2008

External selectors as engines and how to create your own library

With "Sizzle event", the challenge about libraries will move from the coolest/fastest selector engine into the coolest/fastest way to use it for library purpose.

Since Sizzle will be just one of them, thanks to our natural behavior ( read: re-create the wheel ) it is possible that there will be more selector engines around the net.

So, why we could not create our own library that does just what we need and nothing else, maintaining a decent size and performing like a jaguar :D ???

Here a truly basic example about how to create your own library, basing it over a generic selector engine or generic library (or just its engine, if you prefer one)

// our wonderful library constructor
function myQuery(){
// just in case we prefer another name for the constructor
// this code is "name proof"
var callee = arguments.callee;
return this instanceof callee ?
this :
callee.prototype.init.apply(new callee, arguments)
;
};

// add some native prototype to created array like instances
// a common pattern for DOM based libraries
with(Array.prototype)
myQuery.prototype = {
constructor:myQuery,
length:0,
pop:pop,
push:push,
shift:shift,
slice:slice,
sort:sort,
splice:splice,
unshift:unshift
};

// add "not standard yet array prototypes", if necessary, or our own cool proottypes
myQuery.prototype.forEach = Array.prototype.forEach || function(Function, self){
for(var i = 0, length = this.length; i < length; i++)
(i in this) && Function.call(self, this[i], i, this);
};

// define the init prototype to use the pre defined engine
myQuery.prototype.init = function(){
var self = this.engine.apply(null, arguments);
this.push.apply(this, self instanceof Array ? self : this.slice.call(self, 0));
return this;
};

// define the engine for this library
myQuery.prototype.engine = Sizzle; // or jQuery

onload = function(){

// enjoy your lib
myQuery(".foo .bar").forEach(function(HTMLElement){
HTMLElement.innerHTML = "Hello Lib!";
});

};


Summary


The main limit is the engine itself, or better, arguments that the engin could accept.
If we change engine and this accepts different arguments or same arguments in a different way, we need to change every call to our library but at least everything else will work without problems.
For this reason it is reasonble to choose a common engine arguments model, like Sizzle, for example, presuming other engine will accept the same list of options and will produce an array like result.
Am I suggesting to avoid famous/common library? Absolutely no, I simply think the selector engine is the most important thing for whatever DOM purpose library :-)

1 comment:

Anonymous said...

Hi Andrea,

I noticed some silence on your website, hope you're okay. Happy newyear!!! :)

Regards,
Marc