thoughts, ideas, code and other things...

Tuesday, June 01, 2010

Extending the DOM for more functionality

Reading some ExtJS examples today, I came across this -
function highlightWindow() {
var win= Ext.getCmp('myWindow');
var winBody = win.body;

How beautiful is highlightWindow.defer(1000) :) It causes the function call to delay by 1s.

Something like this would be elegant compared to plugging in setTimeouts everywhere in your code. On some further exploration I found that I can extend functions too, I had seen one such useful extension of String class using = function() {...

We can do such things with functions too, for e.g this snippet would add a delay function to any existing functions -
Function.prototype.delay = function(ms){
setTimeout(this,ms); // call yourself after given delay
So now we can have a nice way to delay a function - eg. doMyWork.delay(5000) :)
Function.prototype.delay = function(ms){
setTimeout(this,ms); // call yourself after given delay

function foo(){
// just append some message to an element
document.getElementById("progress").innerHTML += "foo() got a call";

function doWork(){
document.getElementById("progress").innerHTML +=
"delaying foo() for 1000ms";
Another interesting use-case -
Lets say we wish to convert an array into CSV, we could let that be held inside array itself and call is like myarray.toCSV(), like this -
Array.prototype.toCSV = function(){
var csv = new String();
for (i=0; i<this.length-1; i++){
csv += this[i].toString() + ", ";
csv += this[ this.length-1 ].toString();
return csv;

Ah and you can even have your own DOM appender -
Element.prototype.append = function(message){
this.innerHTML += message + "<br />";

A working demo here -
Further reading - Six missing functions in JavaScript arrays



Post a Comment

Subscribe to Post Comments [Atom]

<< Home