Global variables in JavaScript

It’s normal to get caught in the web of global variables, while working with JavaScript. Global variables tend to make the code less readable and maintainable. Douglas Crockford suggests a pattern that can be used to maintain global variables in our code.

Let’s say you have the following code.

var userName = "";
var password = "";
var userType = "";

function loadCredentialsFromLocalStorage(){
 userName = localStorage.getItem("userName");
 password = localStorage.getItem("password");
 userType = localStorage.getItem("userType");

The global variables userName, password and userType variables can be written as:

               userName : "", 
               password : "", 
               userType : ""

function loadCredentialsFromLocalStorage(){
 AGLOBALNAMESPACENAME.user.userName = localStorage.getItem("userName");
 AGLOBALNAMESPACENAME.user.password = localStorage.getItem("password");
 AGLOBALNAMESPACENAME.user.userType = localStorage.getItem("userType");

In the code above, you can create a variable giving it a Global namespace name and have all the ‘actual’ global variables assigned to it. The declaration of the global variables can be moved to a separate file as well. Hence the code becomes lot more readable and easy to maintain.


Video sessions on Sencha Touch 2.0

Starting from next week you can view a 10-15 mins(upper limit) video sessions on working with Sencha Touch 2.0 library. The sessions will be hosted on YouTube and will be made accessible from this blog and DuraSoft site. The video sessions will be simple, short and concise.

The objective is to make you comfortable developing mobile web applications using Sencha Touch 2.0.

Let’s crack some real code!!!


Simple MVC application using Sencha 2.0

My first video post on creating a simple MVC application using Sencha Touch 2.0. Have fun!!!


GuessingGame with Backbone.js

I have a set of examples that I always love to implement whenever I learn a new framework/language/technology. One of them is a Guessing Game. The application will generate a random number between 1 and 100. The user will play the game till he guesses the number correct. The screenshots for the game looks like below:

The UI of the application present inside the body tag is given below.

	   <h1>Welcome to the guessing game. Enter a number between 1 and 100.</h1>
		Enter your guess <input type="text" id="guessTB">
		<input type="button" value="Guess" id="guessBTN">
		<h3 id="messageH3"></h3>
		<h3 id="attemptsH3"></h3>

Let’s implement this game using Backbone.js. In my earlier post on Backbone I had discussed the basics of model, collection and view. We’ll use them to implement the guessing game.

Let’s define a model called GuessingGame with target, attempts and message attributes. ‘target’ attributes will get initialized to a random number between 1 and 100. The GuessingGame model will have a play method that has the core logic of the application. The GuessingGame model is shown below.

var GuessingGame = Backbone.Model.extend({
	defaults : {
		      target : 0,
		      attempts : 0,
		      message : null
	initialize : function(){
				var target = Math.floor(Math.random()*100);	
        play : function(guess){
	                        var target = this.get("target");
                    	        var attempts = this.get("attempts");
  	                        var message = null;
	                       if(guess > target)
  		                  message = "Aim Lower";
	                       if(guess < target)
		                  message = "Aim Higher";
	                       if(guess == target)
		                  message = "You have got it!!!";

In the document load function let’s create an instance of GuessingGame model. You’ll also create a View ‘GameView’. The GameView will have the event handler for the button click event. The onload function with the above logic is shown below:

		var game1 = new GuessingGame();	
		var GameView = Backbone.View.extend({
				el : $("body"),
				events : {
					  "click #guessBTN" : "play"
				play : function(){$("#guessTB").val()));
						$("#attemptsH3").html("Attempts: " + game1.get("attempts"));
				var gameView = new GameView();

There we go!!! I have not done things like validations etc., to keep it simple. GuessingGame is a kind of application that gives you the confidence to proceed to the next level of learning a new tool.


Dive into Android development – VII

In the earlier post we discussed the use of intents to perform call up and sms operations. In this post let’s discuss invoking camera and voice recorders using Intents. You’ll have two buttons Camera and Voice record clicking which will perform the appropriate actions.

On clicking the camera button you’ll create an Intent with the ACTION_IMAGE_CAPTURE action present in the MediaStore class as shown below.

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

The above code will launch the camera application and you can click a picture now.

On clicking the voice record button you’ll create an Intent with the RECORD_SOUND_ACTION action present in the Media class as shown below.

Intent recordIntent=new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);

The above code will launch the Voice Recorder application. You can start recording the voice now.

One of the challenges I have faced in working with Camera and Voice recorder is the control coming back to our application. It varies with the application. I have a Samsung Galaxy S device, where the default voice recorder application doesn’t return back to my application after the job. I have to press the back button to get back to my application.