Shortlink

Modularize JavaScript with Backbone

The jQuery code that I have used in projects have always had modularity issues. The code looks clumsy and messy making it very difficult to maintain. My work with Ext JS4 and Sencha Touch made me looking for a MVC implementation with jQuery code. I landed up with Backbone.

Backbone is a JavaScript library that provides an excellent facility to modularize the client-side JavaScript code. It provides a solution to implement MVC pattern. You can modularize the code by creating models and views resulting in highly reusable code.

I have a very simple application implemented where I display a list of countries in a ul tag using jQuery. I wrap up this whole exercise using Backbone.

To begin with you need to have the scripts Backbone.js, jquery.js and a dependency library UnderScore.js included in my file as shown below.

 <script src="jquery-1.6.1.js"></script>
 <script src="underscore-min.js"></script>
 <script src="backbone-min.js"></script>

I define a Model class called Country and a collection of Models called ‘Countries’. I use the Backbone.Model.extend and Backbone.Collection.extend syntax as shown below.

var Country = Backbone.Model.extend({
	defaults : {
			name : "--",
			capital : "--"
	    	   }
});
var Countries = Backbone.Collection.extend({
	model : "country"
});
var countriesInAsia = new Countries([
	  new Country({name:"India",capital:"New Delhi"}),
	  new Country({name:"SriLanka",capital:"Colombo"}),
	  new Country({name:"Japan",capital:"Tokyo"})
]);

Let’s display the countriesInAsia in an unordered list using jQuery. You can define a view class using Backbone.View.extend syntax. This class has an initialize and render method that renders the countriesInAsia in an UL tag. The UL tag is rendered inside the body element. Backbone view holds the container inside which you want to render the UI in an “el” element. In this case “el” is the body element. The code is shown below.

$(function(){
  var CountryView = Backbone.View.extend({   
        el : $("body"),		
        initialize: function(){
       	       this.render(); 
    	}, 
	render: function(){
      	     $(this.el).append("<ul id='countries'></ul>");
	     for(i=0;i<countriesInAsia.length;i++){
		$("ul#countries").append("<li>" + countriesInAsia.at(i).get("name") + "</li>");
	     }
        },
	changeColorToRed : function(event){
		$(event.currentTarget).css("background-color","red");
	},
	changeColorToWhite : function(event){
		$(event.currentTarget).css("background-color","white");
	},
       events : {
		"mouseover li" : "changeColorToRed",
		"mouseout li" : "changeColorToWhite"
       }
  });		
					 
  var countryView = new CountryView();
});			

What’s amazing is the event handling facility. The events property just lists down the possible events and their listeners. It cannot get better than this.
One of the finest frameworks to write highly maintainable JavaScript(particulary jQuery) code. I am planning to write few more posts on this framework.

Shortlink

Dive into Android development – VI

Let’s develop a simple Android application to perform dial-up and SMS operations. Let’s have two buttons “Call” and “SMS” as shown below. Clicking these buttons will perform the appropriate actions.

The resource layout file for the two buttons is given below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.13" >

    <Button
        android:id="@+id/callBtn"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="50dp"
        android:text="Call" >
    </Button>

    <Button
        android:id="@+id/smsBtn"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="120dp"
        android:text="SMS" >
    </Button>

</RelativeLayout>

Performing dial up and SMS operations involve use of Intents in Android. Intent is a simple class that encapsulates an action and data. For example Dial, Sms, Capture image are all actions that you want to perform. Wrap this information and associated data in a Intent object and launch an activity using it. Intent sends a message to the underlying Android system which triggers the necessary activity. So to dial a number you can use Intent.ACTION_DIAL as shown below.

Intent callIntent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:12345678"));
startActivity(callIntent);

The phone number and the action are wrapped in an Intent object and launched using startActivity method. This will automatically take you to the dialer screen.
To send a message you can use Intent.ACTION_VIEW with some additional information as shown below.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("sms_body", "Hi!!!");
smsIntent.putExtra("address", "12345678");
startActivity(smsIntent);

You can set the intent type to the MIME TYPE “vnd.android-dir/mms-sms”, and also provide the addresses and the message body.

The complete code of the activity class is shown below.

public class DiveIntoAndroid6Activity extends Activity {
	private Button callBtn,smsBtn;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		callBtn = (Button)findViewById(R.id.callBtn);
		smsBtn = (Button)findViewById(R.id.smsBtn);

		callBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent callIntent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:12345678"));
				startActivity(callIntent);
			}
		});
		smsBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				Intent smsIntent = new Intent(Intent.ACTION_VIEW);
				smsIntent.setType("vnd.android-dir/mms-sms");
				smsIntent.putExtra("sms_body", "Hi!!!");
				smsIntent.putExtra("address", "12345678");
				startActivity(smsIntent);
			}
		});
	}
}
Shortlink

Multiple data sources in Grails 2.0

One of my favourite features in Grails 2.0 is the support for configuring multiple data sources. I remember playing with the spring resources to configure multiple data sources in one of my client assignments. Grails 2.0 brings in a built-in support for this.
You can go the DataSource.groovy and configure many datasources like below

environments {
    development {
        dataSource {//DEFAULT data source
            
        }
	dataSource_users { //Convention is dataSource_name
            
        }
	dataSource_sales {
            
        }
    }
    production {
        dataSource {
        
	}
	dataSource_users {
            
        }
	dataSource_sales {
            
        }
    }
}

You have 3 datasources configured, the ‘DEFAULT’, ‘users’, ‘sales’ in for development and production environments.
If you have two domain classes ‘Role‘ and ‘Product‘ mapped to table in ‘users’ and ‘sales’ data sources respectively, you can write it as

class Role{
    static mapping = {
          datasource 'users'
    }
}
class Product{
	static mapping = {
		datasource 'sales'
	}
}

If the datasource is not specified in the domain classes it will use the ‘DEFAULT’ datasource.
You need to be careful while using the service classes, because service classes provide transactional support to the default dataSource. You can change it by using static datasource = ‘name of the datasource’ in the service class.

Shortlink

Function Statements and Expressions in JavaScript

JavaScript is not really taken very seriously as a programming language, when it has to be. This statement comes to my mind whenever I read the book JavaScript, Good Parts.

In JavaScript you can define a function as a statement or as an expression.ie.,

   function eat(){ document.write("Eating"); }//Statement
   var eat = function(){ document.write("Eating"); }//Expression

The main difference between the two comes in the use of the function. A function declared as a statement can be used anywhere in the script ie., even before the declaration like

      eat();//prints Eating
      function eat(){ document.write("Eating"); }//Statement

The same code will throw an error if the function were declared as an expression.

      eat();//Uncaught TypeError: Property 'eat' of object [object DOMWindow] is not a function
      var eat = function(){ document.write("Eating"); }//Statement

So we’ll have to either stick to using functions as statements or expressions in the code. Need to be careful when we use both.

Shortlink

Gradle your Java app

Working with ANT has always been a slightly boring experience for me because of it’s rigid XML syntax. Setting up classpath, tasks like clean, compile, run tests etc., every time is a tedious process.
Ever since I started working with Groovy I started looking at a build tool known as Gradle. Gradle is a Groovy script that can be used to automate the build activities of your project. Let’s see how to build a simple Java project using Gradle.

You can download Gradle and add the bin folder to the path. I have a simple project ‘GradleEx1″ with the following project structure.

The src folder will have a class Hello with the following code.

package com.durasoft;
public class Hello{
	public String sayHello(String name){
		return "Hello " + name;	
	}
}

The tests folder will have a test case HelloTest with the following code.

package com.durasoft;

import org.junit.* ;
import static org.junit.Assert.* ;

public class HelloTest{

	private Hello helloObj = new Hello();
	
	@Test
	public void testSayHello(){
		assertEquals(helloObj.sayHello("Sam"),"Hello Sam");
	}
}

Let’s create a build script build.gradle in the GradleEx1 folder. This gradle file will have a groovy script where you will specify the tasks compile, run tests and package them in a jar file. While doing that you will also add reference to JUnit library.

The build.gradle file is shown below.

apply plugin:'java'

version = "1.0"

repositories {
  mavenCentral()
}
 
dependencies {
  testCompile group: 'junit', name: 'junit', version: '4.8+'
}

sourceSets {
	main {
		java {
			srcDir "src"
		}
	}
	test {
		java {
			srcDir "tests"
		}
	}
}

Is that all??? Yes. All I have done is specify the source folders and the dependencies from maven repository. So what about the compile, run tests, jar etc? The single line apply plugin:’java’ does the trick. It gives you built-in tasks like compileJava, test, jar etc., associated with any ANT build. Here’s where the ‘convention over configuration’ paradigm of Groovy/Grails comes into picture.

So how do we run this? Go to command prompt and run gradle test from GradleEx1 folder.

You can also run gradle jar to create GradleEx1-1.0.jar file. Have a look at the build folder generated in GradleEx1 folder.
Gradle is pretty simple and straightforward and makes use of the DSL capability of Groovy. It’s definitely a welcome change in configuring builds.