08.175 Very Handy Javascript Techniques
Using with keyword to shorten your code
“with” keyword becomes extremely handy when you need to use many attributes of an object without keep calling the object
var house = {
paint: "blue",
size: "big",
hasYard: true,
numberOfLivingRooms: 2,
numberOfStoreRooms: 1,
numberOfBedRooms: 4,
numberOfKitchen: 3,
masterArea: {
hasBedRooms: true,
masterAreaBedRooms: 3
}
};
When you want to find the number of rooms in house, normally you would need to
var numberOfRooms = house.numberOfLivingRooms + house.numberOfStoreRooms +
house.numberOfBedRooms + house.numberOfKitchen;
By using with the code will be much more elegant and faster
var numberOfRooms = 0;
with( house ) {
numberOfRooms = numberOfLivingRooms + numberOfStoreRooms +
numberOfBedRooms + numberOfKitchen;
};
Additionally, you can also have nested with keyword
var numberOfRooms = 0;
with( house ) {
numberOfRooms = numberOfLivingRooms + numberOfStoreRooms +
numberOfBedRooms + numberOfKitchen;
with( masterArea ) {
numberOfRooms += masterAreaBedRooms;
}
}
Using String.indexOf() function to replace comparisons in if else
If you have something like the following if else code, you can consider using String.indexOf() as an alternative
if( inputType == "text" || inputType == "password" || inputType == "checkbox" ||
inputType == "radio" ) {
// Do something
}//end if
You can replace the above by the following
if( "text|password|checkbox|radio".indexOf( inputType ) >= 0 ) {
// Do something
}//end if
This would make your code more readable and easier to understand
Call Back function to be used to extend a function in team project
Sometimes, when you work in a team, after you have developed some function, your team mate will ask you whether he can call and use some variables inside your function. If you don’t want him to touch your code, here is the solution. You can provide him a so called “Call Back function”, so that he can throw in his function to call after your function has been completed. Here is an example
Assuming you have a function called retrieveDataFromTheInternet
function retrieveDataFromTheInternet( auditProfitCallBack ) {
var data = sendHttpRequestTo( "http://somepage.com" );
var initialData = formatDataToExcel( data );
var profitForThisMonth = processProfitForThisMonth( initialData );
....
if( typeof auditProfitCallBack == "function" ) {
auditProfitCallBack( profitForThisMonth, initialData );
}
}//end retrievedataFromTheInternet
Your team would call your function together with his function as an argument
retrieveDataFromTheInternet( function( profitForThisMonth, initialData ) {
// Do something with profit for this month
// Verify initialData
});
As you can see, your team mate can use some of the private data and variables inside your function without knowing what happens in your code. This is very convenient in a team where variable resources are shared among many people. You could also have multiple Call Back functions, however, it will make your code harder to read and debug.
Use span tag in html code to create an object in javascript
Normally, when you have a div tag in html code, for example
<div id = 'mydiv' name = 'mydivname'>This is my div</div>
If you want to retrieve this div in Javascript, you need to use the following code
var myDivObject = document.getElementById("mydiv"); // Dom Scripting Way
var myDivJQueryObject = jQuery("#mydiv"); // jQuery Library way
var myDivPrototypeObject = $("mydiv") // Prototype Library way
However, sometimes, you could use span instead of div and it can achieve the same purpose. The direct benefit of using span is very interesting. Instead of querying using the above code, the span tag will be itself a javascript Dom Object after its HTML has been rendered. Hence, you can save a query for a DOM object. For example,
<html>
<body>
<span id = 'myspan' name = 'myspanname'>This is my span</span>
...
<script language = 'javascript'>
alert( myspan.innerHTML );
// Pop up an alert with content This is my span
</script>
</body>
</html>
This works in all browsers under the Sun
Use famous supplant function to get rid of string concatenation in Javascript
I see a lot of Javascript programmer still uses a lot of string concatenations in Javascript code. This has been proven not very memory efficient each of the concatenation is an operation. For example,
var formTitleHTML = "<div class = '" + formTitleClass + "' name = '" +
assignedName + "' id = '" + assignedIdFromServer + "'>" +
formTitleContent + "</div>";
This assignment requires 8 String concatenations before assigning the final String to formTitleHTML. And let say if you have a lot of formTitleHTML variable need to be assigned, it would become very tedious for each time you need to create a formTitleHTML using some predefined variable. Fortunately, the good news is there is a function called supplant written in Javascript that can help you rewrite these things in a very elegant way. This function is written by Douglas Crockford - Javascript Architect in Yahoo!. Following is the supplant code
function supplant( str, obj ) {
return str.replace(/{([^{}]*)}/g,
function (a, b) {
var value = obj[ b ];
return isStringOrNumber( value ) ? value : a;
}
);
}
function isStringOrNumber( a ) {
return typeof a === "string" ||
typeof a === "number";
},
The after that, you can define a template like the following
var myFormTitleHTMLTemplate = "<div class = '{formTitleClass}'
name = '{assignedName}' id = '{assignedIdFromServer}'>{formTitleContent}</div>";
// Then afer that you can do
var myFormTitleHTML = supplant( myFormTitleHTMLTemplate,
{
formTitleClass: "green-form-title-class",
assignedName = "my-form-name",
assignedIdFromServer: "1984",
formTitleContent: "My Awesome Form"
}
);
Another benefit of using this is that, it can save you a lot of troubles in the future if you need to change the template. You only need to change the template only one, versus you need to change line by line in previous implementation.
Del.icio.us | Digg it | StumbleUpon | BlinkBits | Furl | Ma.gnolia | Newsvine | Reddit

So many techniques I haven’t known before. Thanks a lot!
August 17th, 2008 at 5:01 am