Cordova (Phonegap) , alert message.

This might seem, very easy task. But then while making a customisable alert message, one need to think as to how to do it. While working on Cordova(phonegap), one can easily assume and which is true is the javascript alert script.

alert("Hello!");

The javascript alert will work. Then we do not have a customisation option except for the message. The solution Cordova provides is a function with the name as alert. The syntax is as below.

navigator.notification.alert(message, alertCallback, [title], [buttonName]);

In the very basic form, where one need to have a specific title, message and button name, the code I use is

navigator.notification.alert("My message", undefined,"My Alert", "ok");

Thats the simplest kind and if one need more generic, wrap the whole thing inside one of your own custom function as example below.

function showAlertWithTitle(title,message){
	navigator.notification.alert(message, undefined,title, "ok");
}

Hope coding.

Things to consider for Cordova (phonegap) development

This came to me as a learning from my first Cordova(phonegap) application development.
The first thing one comes across while developing in Phonegap is “the need for a GUI lib” and the first thing to get in a search result is jQuery, its mobile version and the UI lib. There are many other good libs out there, but this one seems quite ok. While one may choose to use a UI lib or build own lib its up to the developer. In my experience its easy to get started with jQueryMobile and its UI, which uses “Theme roller” to theme the UI.
If one is using jQueryMobile then the trick is to try and solve all the UI problems with this lib itself (not hacking the CSS and JS all over the place in the project). That way the performance will be more and pain to solve all the UI problems is less.

One can just start to make one Cordova application without any libraries, but to be productive soon, the minimum required libraries are
1. jQuery
2. jQueryMobile
3. cordova

Now the most important library which might not be required for the project as a project dependency but is a real time saver is
1. UnderscoreJS
After some playing around with the library and from the suggestion from the community I found Lo-Dash library, which is a drop-in replacement for UnderscoreJS with performance enhancements. So I would recommend using
1. Lo-Dash

Now to coding tips, if one knows the “scope” and “this” in javascript, then writing javascript applications are just fun. So prepare yourself with javascript and how it works, so as to make your life easier developing the application.

Target platform and the library support :
The current Cordova lib might not support your required target platform !! Yeah, that is another thing which might take up sometime to know in the beginning. With each release these libraries kind of deprecate support for old platforms, so check that out in the beginning itself.
The same goes for jQuery and jQueryMbile. Check out whether the latest version of the library supports your target platform.

Native Notifications in Cordova is not supported :
Cordova (phonegap) does not support native notifications. It only supports “alerts”,”confirm” (kind of alert only),”beep”(sound) and “vibrate” (device vibration). But then if you expect to do “alert” notification as iOS and Android devices do (like showing the alerts to user when the application is running in background), then Cordova (phonegap) does not help. One has to write native libraries in native languages and call them from javascript through Cordova.

jQuery tips :
Adding an element to a page and displaying it :
jQuery “append()” and “prepend()” does not update the UI (or DOM), so the added elements are not visible by default. we can hack it by dispatching a jQuery event called “create”, the code will look as below

$("#p_4_content").prepend("hello World").trigger( "create" );

That will tell jQuery to render the UI again, resulting in displaying the added item.

Defining EventHandler Scope :
Another nice thing is calling the event handler in required “scope”. The jQuery library provides a handy method for adding event event handlers as

$('#id_btn').on( 'tap', onBtnTapped );

But then it will be scoped to the same scope as where its being written. If you are writing things in an Object, you might want to get the “scope” in the handler(which is “this”), in order to do that, jQuery provides a “third” parameter option, and one can pass the scope in there. The optional parameter is at the middle instead of at the end (as comparing to other object oriented programming convention)!! But then its the way to go. So the modified code will look as below

$('#id_btn').on( 'tap', this, onBtnTapped ); //Look at the middle parameter
//and the handler code looks as below
onBtnTapped :function(event){
    	//just saving the scope, may be we need it in future here
    	var that = event.data; //here event.data=this (which we passed as second param)
    }

That way inside the handler we can get the “scope” as below

var that = event.data;

The second parameter sent while binding the handler to the event, can be got inside the event handler as “event.data”. Since we are just passing “this”, we can get that in the handler as the example shown above.

Writing the EventHandler :
Well, now the trick writing an eventhandler without making the application behave unreasonably is a challenge. It might sound silly but it is not. If you write an event handler as

onBtnTapped: function(event){
    	//Do something
    }

Then its bound to get in your way of the behavior of your application. The jQuery fix is to do a “return false” in all the handlers. But then that might not be the case of your handler as that might return in between the code itself. So the fix is make a call to “preventDefault” as soon as you are inside the handler method. the modified code will look as below

onBtnTapped: function(event){
        event.preventDefault();
    	//Do something
    }

That is the start, I will post more tips as I fight through the scenarios.

BackboneJS : the basics

This is my first javascript framework for application development and this post is supposed to be for anyone who is just beginning with this framework. While I am still learning this framework, the points here should make one comfortable at least to get started in learning the framework itself.
First things first, here is a slide show of a talk I had given to a group regarding BackboneJS. The source code for the same slideshow (which is made with backboneJS itself) is available here.
Well, to start with BackboneJS in itself provides a structure to the web application development. It is heavily dependent on UnderscoreJS and RequireJS. RequireJS allows us to use javascript modules and load script files at one point in a .js file rather than the script tags in an html document. UnderscoreJS provides very nifty utility to ease our javascript development.
BackboneJS is supposed to be a model-view-controller framework and while we can call it like that but the real “C” here stands for “Collection”.
The view class here in BackboneJS is kind of controller. Once got the data, it can make other views or can decide which view to render at what position on the html page. There is a concept called “template” and Underscore gives that facility to us as we are developing in BackboneJS. These templates are kind of placeholders for content and once we got data, we can render html with the help of these templates.
Collection class actually is a glue between frontend and backend as its responsible to get data from server and set data in server.
I would say it a quite straight forward framework, though it takes some time to get used to the behavior of the framework. Who come to javascript frameworks for the first time will take sometime to get used to it. Though the documentation is quite good in the official website, there are things which are not documented, so it will take some time to search and undertand the concept. Overall I would say an elegant framework.
Happy coding

CoffeeScript, the first taste

On my path inside javascript land, I came across CoffeeScript which compiles to JavaScript. One week of handson to the language and I tried to write a simple phonegap application with CoffeeScript taking jQueryMobile into action. The whole project is on github, the whole of the CoffeeScript is here for your reference.

First thing I liked about the language is, it compiles to a very decent, rather I would say the best handwritten JavaScript. That itself is a huge advantage if one wants to learn JavaScript.
The code is modular and compiler is straight forward so its an immediate likable thing if one wants to code ahead in JavaScript. The community is vibrant and the official documentation itself is quite nice.
It is a must try for any javascript developer.

Things to keep in mind, and must be kept in mind while coding in CoffeeScript, are
1. The indentation should be exactly same
2. Each function returns the lastline of code in the function
(I faked it in above code by writing “null” at the end of each function)

Happy Coffee

Dartlang for devices with Rikulo

While working with Rikulo is as straight forward as working with any other packages of Dart, to make this work in devices, one has to keep following things in mind.
First of all “Rikulo” itself is not capable of doing device level development, rather it depends upon “phonegap” (now cordova) and to compile against this, there is another package named “Rikulo Gap“. So the basic pub setup looks as this.

dependencies:
  rikulo:
  rikulo_gap:

Once installed the development process is straight forward as Dart itself while taking advantage of the Cordova APIs.
Upon completion of the development process, jump into “Dart to Javascript” compiler and generate the javascript file for the project. Fortunately thats as simple as going to “Tools” menu and clicking “Generate Javascript” in the Dart Editor. One has to select the “.dart” file first, for which the javascript file has to be generated. Upon successful generation of the file, the generated file name would be something like “myProject.dart.js”.
Now you have to add this “js” file in your “html” file like the usual “script” tag. That means to deploy to Cordova, you have to add two script tags as below.



Once done, open up the Eclipse or which ever IDE you are using to develop the Cordova (phonegap) applications, copy the “.html” and “.js” file into the respective folders of the Cordova project.
Lastly, but most importantly, remove the version number from the cordova JS file (for example cordova-2.3.0.js to cordova.js).
Now we have a workable native application built with Dart, Rikulo and Cordova.

Happy Darting !

Some interestin Dartlang packages

There are various packages with different intentions are available to Dartlang in a global space known as “pub“. At present there are two of these packages which seems interesting to me.

  1. Dartflash
  2. Rikulo

As you might be already guessing that “Dartflash” is a port of Flash API to Dartlang. That makes any flash developer instantly play with “canvas” element of HTML5. So yes, its not working on the DOM of the page rather works on the “canvas” element of the DOM.
The second one, that is “Rikulo” seems to promise a lot. It says, it can create “cross-platform web and native mobile applications using HTML5″, while its true to create web applications, but the native mobile application is done through, you guessed it right, phonegap(now known as CORDOVA). And now there is another dart package,which is the port of CORDOVA in Dartlang. Its known as

  • Rikulo Gap
  • That means, one has to have the “Phone Gap” development environment ready to start doing mobile development.
    Rikulo works in DOM manipulation and gives a displaylist hierarchy (if one compare it with flashplayer displaylist, its similar in concept and how it works).

    Some interesting Dartlang packages

    There are various packages with different intentions are available to Dartlang in a global space known as “pub“. At present there are two of these packages which seems interesting to me.

    1. Dartflash
    2. Rikulo

    As you might be already guessing that “Dartflash” is a port of Flash API to Dartlang. That makes any flash developer instantly play with “canvas” element of HTML5. So yes, its not working on the DOM of the page rather works on the “canvas” element of the DOM.
    The second one, that is “Rikulo” seems to promise a lot. It says, it can create “cross-platform web and native mobile applications using HTML5″, while its true to create web applications, but the native mobile application is done through, you guessed it right, phonegap(now known as CORDOVA). And now there is another dart package,which is the port of CORDOVA in Dartlang. Its known as

  • Rikulo Gap
  • That means, one has to have the “Phone Gap” development environment ready to start doing mobile development.
    Rikulo works in DOM manipulation and gives a displaylist hierarchy (if one compare it with flashplayer displaylist, its similar in concept and how it works).

    Two absolutely necessary Node packages, within a week of Nodding

    As my learning continues with NodeJS, it is now becoming obvious to me that probably I could never live without Node in future from now on, even if I do not continue developing on NodeJS. In just about a week there are the below two packages which became absolutely necessary for me in day to day work, while doing front-end web work or just playing around with javascript in general.
    serve
    nodemon
    These two enable any folder to act as a web server. Once installed from “npm” one can directly fire up these commands and see the folder as a website through a browser.
    If you want to run the webserver at port “1234″, just navigate to the folder you want to serve as a website and fire up the command below.

    serve -p 1234
    

    If you do not care about the port, just

    serve

    will do the job, where the site will be served at a default port “3000″.
    Now to access the website go to “http://localhost:3000/” in your favorite browser.
    If you change a file, you have to manually restart the server.
    Now “nodemon” helps us in automatically restarting the server on any file change. If one is working on any web application and does continuous changes to the files, one just have to refresh the webpage (No need to restart the server over and again for updates). That gives continuous focus on development.
    Happy Nodding :)

    On my search for a JS variant, triggered by NodeJS study

    Well while going ahead with my NodeJS study and after looking at the functionality that NodeJS provides, I got a little curious to search for something which might help me develop in JS a little more easily. To my surprise, I found a lot of languages which does that, but I picked 3 as it seemed these are got some history to themselves and backed by big corporate or have a huge community to support.
    1. CoffeeScript
    2. TypeScript
    3. Dart
    All these three compile to javascript. While CoffeeScript and TypeScript are nodeJS dependent and installed by “npm”, Dart comes with its own installation and IDE. Personally I liked the first two, at first glance as they are installed with “npm”. But then Dart comes with its own IDE, which is an advantage.
    Now a little bit about the face value of the three.
    CoffeeScript : A huge community and has proven history of a good player.
    TypeScript : Its a microsoft initiative.
    Dart : Its a Google initiative.

    Looking at all these, I still feel HAXE is the best for JS dev too, may be thats my biased opinion.

    Modules in NodeJS

    There is this concept of Modules in NodeJS, which is kind of but not exactly the same as Class concept of programming languages like Java and ActionScript. To add a module the syntax is

     
    require() // its like import in Java and Actionscript
    

    A detailed implementation of “require()” statement is as below

     
    var myModule = require('./myModule.js');
    

    So that’s all to include a module, if the module JS file and your application JS file are in the same folder, for the time being lets do the understanding this way. :)
    Now lets see what kind of features or flexibility “modules” gives us as a nodeJS developer.
    If we think of modules as the Classes then it will be easier for us to understand.
    First of all, everything inside a module is private. Ohh yes, private things in javascript. Thats interesting, is not it!
    Lets write a simple class kind of thing in a module, which has a private property and getter-setter method of the same.

    stupidVar='Global Scope. Avoid this.';// Never put anything in Global Scope
    var nameOfModule='I am private';
    exports.getName=function(){
    	return nameOfModule;
    }
    exports.setName=function(newName){
    	nameOfModule=newName;
    }
    

    Couple of things to note here. First of all every variable that is not declared with “var” is on the Global scope. I think thats true in general for javascript. Apart from this anything else in a module is private, that means the variable “nameOfModule” in our example is only accessible from inside that module itself. If we try to access it from out side the module NodeJS will throw an error. Now to expose methods and properties to outside world, we have to add the methods and properties to an object named “exports”.
    Now to consume the module, lets write a “main” class which we can assume as the application entry.

    console.log("Hello Modules.");
    var modOne=require ('./modOne.js');
    console.log(modOne.getName());
    modOne.setName("I am set by the setter. Setter is Public.");
    console.log(modOne.getName());
    //console.log(nameOfModule);// this will throw an ERROR as we are trying to access private var
    console.log(stupidVar);
    

    Save both the files in the same directory. Open the commandline and navigate to the directory. To run our application we have to write

    node main
    

    Just a note that we do not have to specify “.js” after the “main”, while feeding the file to NodeJS.

    The source files for this are here to download.
    [reference : net.tutsplus.com ]
    Now there are publicly available packages, libraries and modules in our case. To install a module in a nodeJS application, one has to navigate to the folder containing the application through commandline and install the required module. An implementation detail is as below.

    npm install module_name
    

    I hope you remember “npm” from previous tutorial. For a quick reminder, “npm” and “node” both the tools are installed by default when we have installed nodeJS. The “npm” is the package manager for nodeJS.

    Happy Nodding :)