Substitute for the for loop
March 26th, 2008 Filed Under Good to know, Javascript, comparisons, gyan
Today I came to know a new trick of looping collections. Generally we do a for loop and have i or any other variable as the counter. An alternative to this could be something like this:
var ar = [0,1,2,3,4]; //array
while(ar.length != 0)
{
document.write(ar[0]);
ar.shift();
} //displays 01234
If you have a set of nested for loops which in turn calls other functions which has some loop, and if the counter variable name is same then some browsers forget the scope and reinitializes the variable or shows up the latest value that was set by the latest loop before it lands back to the host loop.
This while construct can save you some lines as well as risk of i(can i call it i-risk? like i-pod???)
Isn’t it Good to know !!
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
Delegate in Javascript
March 19th, 2008 Filed Under Javascript, Tips & Tricks, browser, gyan, prototype, snippet
I was just remembering my C#.net days and the concept of delegates, which I think Java doesn’t support natively[please comment if someone knows java does].
So, I thought of sharing my view and the way we can mimic delgates in Javascript to work with HTML.
First let me explain the concept of delegate if someone doesn’t know. A delegate is a function pointer which allows the programmer to encapsulate a reference to a method inside a delegate object. If that was too technical, let me tell you in plain english that a delegate is an object which can call the referenced methods to a procedure where it has been passed.
Before going further, let me put some code here. Just go through it and I will explain what is it.
var _delegate = {};
_delegate.items = [];
_delegate.push = function(f){_delegate.items.push(f)};
_delegate.exe = function()
{
for(di=0; di<_delegate.items.length; di++)
{
_delegate.items[di]();
}
}
In the above code, you can see, the first line declares an object called delegate. The second line has a member called “items”(to be used internally) and two methods called “push” and “exe”.
Where can you use it:
You can use it for a page load event where you are not always sure what are all the functions you need to execute for different pages. So, you have a generic function which gets called upon every page loads. And what you need to do is just “push” the function name as many times you want in your whole page, js files etc.
But onload sucks:
Yeah, that’s true. So you need a DOMReady event for each page, so that everything executes as soon as the DOM is available.
Using the Delegate:
Now for using your delegate you need to include the DOMReady first. Then you can use the delegates as shown:
_delegate.push(fn1);// you add your first function handle _delegate.push(fn2);// you add your second function handle DOMReady(_delegate.exe); // this doesn't change ever
And, when your DOM is ready, all the pushed functions are fired. You must, be thinking - “What’s the big deal?” The big deal is your clean approach to onload execution. In conjunction with DOMReady, you have the easiness of globally having the _delegate object to push at any part of your code.
This is not the only use of delegates. You can have a delegate for any function call, but for that you need to create a constructor rather than a global delegate object. And globally speaking, that would be the better way to use the concept as you would create a new object and then use it. If you want to know that in detail, ask me how.
Please comment your thoughts about this, and let me know if you have a say. Thanks for your time!!
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
DOMReady - The Pro Way
March 19th, 2008 Filed Under Javascript, Tips & Tricks, browser, gyan, jQuery, snippet
I was just digging through the concept of DOMReady used in jquery and found it to be very complicated. Then I started looking for some alternatives. I found the following code from Stuart Colville http://muffinresearch.co.uk :
function DOMReady(f){//THANKS TO STUART COLVILLE[http://muffinresearch.co.uk]
if (/(?!.*?compatible|.*?webkit)^mozilla|opera/i.test(navigator.userAgent)){ // FEELING DIRTY YET?
document.addEventListener("DOMContentLoaded", f, false);
}else{
window.setTimeout(f,0);
}
I am really feeling lucky to have such a concise and foolproof code. I should say its the pro way.
Thought to share with everybody. But one request I have to make that please don’t forget to specify his name and web address while using his code. We should be loyal to each other on the web community to help each other and get recognized for whatever we do.
Post Linx
Permalink | Trackback |
|
Print This Article | 1 Comment
Binaural Brain Waves - the digital drug
March 12th, 2008 Filed Under Spirituals, Technology, gyan
I know this is not the place where I should publish my non-technical gyan. But this is a bit technical too.
Day before yesterday, I was reading through a column in my local newspaper and I came across a phrase called “Digital Drugs”. I immediately googled it, and found an altogether different context of digital drugs - The Binaural Brainwave Beats.
The theory revolves around the theory of EEG(Electroencephalography).
EEG is used to measure brain’s electrical vibrations from the surface of your head. It contains frequency patterns below 30Hz.
They are categorized into four states:
| State | Frequency range | State of mind |
|---|---|---|
| Delta | 0.5Hz - 4Hz | Deep sleep |
| Theta | 4Hz - 8Hz | Drowsiness (also first stage of sleep) |
| Alpha | 8Hz - 14Hz | Relaxed but alert |
| Beta | 14Hz - 30Hz | Highly alert and focused |
All of the frequencies are almost present in all of the mind states listed above. But the dominant frequency is considered to be the actual state of mind.
Commanding your Brain to enter in a desired state:
If you are found to be in Highly alert and focused state(14Hz - 30Hz or Beta state), it is possible to bring you down to the Alpha state by applying a 10Hz frequency as an external stimulus. The effect will relax you.
So how does the stimulus work is the next question came to my mind.
For example if you need to have a stimulus of some frequency for your brain, you need to be fed by that frequency, and it can be absorb by your mind from different sources. Ear is one of the very easily available source and directly does the work. To feed the frequency they use binaural beats technique. This technique feeds two different frequencies from both the channels in a stereo headphone, and does the following to generate a 10Hz stimulus:
Send a 500Hz tone from right channel and send a 510Hz tone from the left channel. The difference is what affects your brain state.
When I read about this, I was just thinking that it is some fooling around business. But actually after using it I felt the difference. I got a deep sound sleep and woke fresh in the morning by using it for 30 minutes in the night.
Although today is my 3rd day, but I can feel the difference.
For this there is a software called BrainWave Generator which can be downloaded from http://www.bwgen.com/download.htm and can be used for the following purposes:
- Increasing Concentration
- Meditation
- Relaxation
- Self-hypnosis
- Insomnia
- Increasing Creativity
Infact, in the Hindu Vedic Theories there is a theory of “Naad” - the sound waves. In the “Saam Veda” it was believed that each and every Naad generated in this universe has some or the other effect on the human mind.
And hence, “Saam Veda” teaches the performing art including chanting, music, songs and dance for the application of theory. The Indic Classical Music(Hindustani and Carnatic style) are the extension to the threads of “Saam Veda”.
Some of you might have also heard about the music therapy in India, where different types of percussions and sounds are generated to have effect on the brain and hence achieve a desired state of mind.
The theory also says that by controlling the state of the mind, we can have control over all kinds of mental illness.
Insomnia, Lack of concentration etc is nothing but the illness of our minds.
So, let yourself give a try to this.
Also in some of the forums, I read that some people felt uneasy after taking the dosage of the therapy. It may be correct. So if you try and feel that its not your cup of tea, then immediately stop using the therapy. Some people are too sensitive to sustain the change in mental state.
But for an exiting experiment you can give it a try.
Note:
- For effective results, be in an isolated place while taking the therapy.
- Minors are strictly advised to take guidance of their parents or Adults.
- You don’t have to listen to these frequencies at a high volume.
- For more information on the theory, you can visit http://www.bwgen.com/
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment
Internet Explorer 8 Beta - Download
March 7th, 2008 Filed Under browser, comparisons, debuggers
Download Windows Internet Explorer 8 Beta for Windows XP
Microsoft has released its Beta version of highly disgussed(disgusting discussions) IE 8. You can download it from the following link. By default you will be prompted to download Silverlight. You can download it if you wish to.
However, this version of browser will not be installed on checked(debug) version of Windows Vista, Windows Vista SP1, or Windows Server 2008.
What does it copy? Copies so many things from Firefox and its plugins.
Restore Session: Just as FF plugin, it restores the previous session of opened tabs if because of some exception your browser closed unexpectedly.
IEr Bug: Just removed the F from the Firebug and has given almost the same functionalities as Firebug plugin for Firefox. Just removed the “flexibility” and ease Firebug provides you. But appreciate the copy, as it will reduce a lot of unwanted efforts for the UI developers.
Compatibility Modes: While debugging, you can change the browser version compatibility to test if it works with IE5, IE7 and IE8… oops missed IE6.. maybe in the final release they will add IE6.
No live CSS edit: As you get a live css edit in Firefox, here you cannot do that. You need to go to each and every element on the HTML tab and turn on or off the applied styles. No way to add new CSS Text.
Inspect: Here it is “Select element by click”, but does pretty much the same thing. Good CTRL + C. But oops… while inspecting in FF on an element the click event is not registered for the element, but it is transferred to Inspector. IE8 … I think thats a bug probably!!
Activities: A good add-on feature that enables your users to find for contextual services like map, restaurants etc etc in place. This is an extendible tool for the users. You can even copy text to you blogs or web pages. Microsoft appreciates copying?? Thats just a prank… but its cool thing to have.
WebSlices: WebSlices is a new feature for websites to connect to their users by subscribing to content directly within a webpage. WebSlices behave just like feeds where clients can subscribe to get updates and notify the user of changes
CSS 2.1: Hmm sounds good
Data URI Support: Now you can embed your images as you can do it in Firefox: <img alt=”Image fed from data url” src=”data:image/png;base64,iVBORw0KGgoAAA…” />. Good to have for the bloggers who don’t want to have images repository anywhere.
Versioning and Cross-document Interaction: This is just what I wished. I told that to Sudipto. Internet Explorer 8 introduces the IE8 standards mode by default—this lets Web designers use the latest rendering features available in Internet Explorer 8. In addition to layout changes, IE8 standards mode will also affect the behavior of scripted APIs (DOM).
To opt-out of IE8 standards mode, the META tag may be used to obtain IE7 compatibility mode:
<meta http-equiv="X-UA-Compatible" content="IE=7">
Whooooo Hoooooo
But we need compatibility with IE6 and Quirks too.
Now the copies from FF3:
AJAX Navigation: Enables users to navigate back and forth without leaving the AJAX application and could be used navigating a page without performing a traditional full navigation. This allows websites to trigger an update to browser components like the address bar by setting the window.location.hash value, firing an event to alert components in the page and even creating an entry in the travel log.
DOM Storage: Concept pretty much around classic asp session variables, but will not be available in previous versions or other browser vendors. This is a simple-to-use method for storing and retrieving strings of key/value pair data. Data can be stored per tab instance for a session or persisted to the local machine. This allows pages to cache text on the machine which reduces the effect of network latencies by providing faster access to pre-cached data. Several innovative uses are possible. For example, use this in combination with the new network connectivity event to allow a page to cache data if it detects that the computer is offline.
Connectivity events allow websites to check when the user is connected to the network and receive notification of connectivity changes. FF you inspire.
Six connections per host instead of two for broadband scenarios and a scriptable property allow for more improved performance by allowing parallelization of downloads in Internet Explorer 8. In addition, this increases functionality by ensuring a request is not blocked to a host if two connections already exist. Websites can optimize their downloads based on a scriptable property.
XMLHTTPRequest Enhancements include a timeout property that can be set to cancel the request if necessary, allowing developers to manage the request better.
Cross domain requests(XDR): A new jargon, but also a feature to communicate across domains. Firefox 3 has also done the same. I am not sure about the code we need to write to allow this feature. But suspect to be different from Firefox … so again and if… else perhaps.
Selectors API: This is the most wanted feature. Copied from jQuery. This enables you to select your web page elements like CSS. For Example:
For selecting some required fields in your form you write something like this:
function doValidation(){ // Retrieve all the required elements by ID
var name = document.getElementById('fld_name');
var empnum = document.getElementById('fld_emp');
var ssn = document.getElementById('fld_ssn');
var ccnum = document.getElementById('fld_ccNum');
var bribe = document.getElementById('fld_cost');
// Set the flag to false by default
var missingRequiredField = false;
// Validate each of the elements
if (name.childNodes[1].value == "") missingRequiredField = true;
if (empnum.childNodes[1].value == "") missingRequiredField = true;
if (ssn.childNodes[1].value == "") missingRequiredField = true;
if (ccnum.childNodes[1].value == "") missingRequiredField = true;
if (bribe.childNodes[1].value == "") missingRequiredField = true;
But now with Selector API you do this:
function doValidation () {
// Retrieve the required elements by using Selectors
// Selects all the form fields with 'required' classes
var reqs = document.querySelectorAll(".required");
// Set the flag to false by default
var missingRequiredField = false;
// Validate that the form data is not empty
for (var i = 0; i < reqs.length; i++)
{
if (reqs[i].value == "") missingRequiredField = true;
}
Coool No?
Whatever it copies doesn’t actually matter too much because, its all the need of the time. And after all its a race. To compete one need to imitate all that is needed.
Post Linx
Permalink | Trackback |
|
Print This Article | Leave a Comment

