Extending the DOM for more functionality
Reading some ExtJS examples today, I came across this -
function highlightWindow() {How beautiful is highlightWindow.defer(1000) :) It causes the function call to delay by 1s.
var win= Ext.getCmp('myWindow');
var winBody = win.body;
winBody.highlight();
}
highlightWindow.defer(1000);
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 String.prototype.foo = 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){So now we can have a nice way to delay a function - eg. doMyWork.delay(5000) :)
setTimeout(this,ms); // call yourself after given delay
};
Function.prototype.delay = function(ms){Another interesting use-case -
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";
foo.delay(1000);
}
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 - http://ideamonk.in/playground/extjs/extension.html
Further reading - Six missing functions in JavaScript arrays
Labels: javascript
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home