I learned a lot about JavaScript today. Check out this little snippet of sweetness:
PHP Code:
<script type="text/javascript">
(function() {
window.$w = window.wayfarer = function(node) {
return new wayfarer.prototype.elementChain(node);
}
wayfarer.prototype = {
elementChain: function(node) {
var arr = [], count = 0;
if (node.nodeName) {
this[0] = node;
count = 1;
}
else
if (typeof node == "array") {
arr = node;
count = arr.length
}
else
if (typeof node == "object") {
for (var o in node) {
if (node[o].nodeName) {
arr.push(node[o]);
count++;
}
}
}
for(var i = 0; i < arr.length; i++) this[i] = arr[i];
this.size = count;
return this;
},
each: function(fn) {
if (typeof fn == "function") {
for (var node = 0; node < this.size; node++) {
fn.call(this[node]);
}
}
return this;
}
}
wayfarer.prototype.elementChain.prototype = wayfarer.prototype;
//thanks to jQuery for this idea
var staticMethods = {
inherit: function(obj1, obj2) {
for(var o in obj2) {
obj1[o] = obj2[o];
}
return obj1 || {};
}
}
staticMethods.inherit(wayfarer, staticMethods);
})();
</script>
What you're looking at is a micro-library. I programmed it to react a lot like jQuery (my framework of choice). Although I did rip some of the ideas more or less directly, almost everything is original.
Obviously, there will eventually be more static methods, but the first static method allows objects to inherit the properties of other objects, which is something you'll find in virtually every framework in one form or another.
The wayfarer object (abbreviated $w) can take any DOM object array, or DOM node as an argument. It then returns the node list in a way that allows prototypes to be built on it, in a special way.
The core function is each(), which anyone who uses jQuery alot knows well. Although the jQuery each() is much more complex, I built mine to function, at least on the most basic level, in the same way. Which means, it takes a function as an arguement, and uses the keyword "this" to refer to the node that is being looped over. My first ever test of this looks like this:
HTML Code:
<html>
<head>
<title>My First Program</title>
</head>
<body>
<a href="/index.php">Home</a><br />
<a href="/about.php">About</a>
<script type="text/javascript">
$w(document.getElementsByTagName("a")).each(function() {
this.onclick = function() {
alert(this.href);
return false;
}
})
</script>
</body>
</html>
Anyhoo...