Sunday, December 23, 2012

Mobile Single Page Application

Intorduction

A few days back I’ve started to think about creating a mobile SPA at work. Now, we work with jQuery Mobile to create mobile apps. jQuery Mobile has some sort of a behavior that can make your website look like a SPA website.

Now, jQuery Mobile looks at each html page for div with data-role “page” and every time one navigates to another page, the next page retrieved by AJAX request and the “page” div is gets injected into the DOM. It also adds a transition animation and thus it looks like the page is changing on-the-fly. There are a couple of potential problems with this technique:

  • The whole html is retrieved per page request resulting in high-bandwidth calls which actually has impact on the amount of data used (which is limited to a couple of GBs per month) and on the speed.
  • You cannot add scripts in the next page outside the “page” data-role div because it won’t get injected to the main page and so won’t exist. Also, the jQuery document.ready event will only fire once on the initial page request, although jQuery Mobile provides another method to deal with this problem (e.g. pagecreate) it’s less convenient.
  • Since more than one page gets injected into the same html document you need to be sure not to use same id attributes in two different pages because it will create more than one element with the same id and will create id conflicts on the DOM.

There is one thing though that in my opinion works very well in jQuery mobile. The mobile UI and layout. It is relatively easy to create and customize the UI with jQuery Mobile. Also, you do not need to worry about device-width issues, since they are resolved automatically by the framework.

So to start with something I had to choose libraries to work with.

So what do we need?

We work extensively with knockoutJS to gain the MVVM behavior in javascript. This framework looks mature enough so no reason to skip it. Now, knockout will also give the ability to use templating ability to dynamically display data. One limitation with the knockout templates is that you can only place them in the same html file they are used in. To handle this we can use another library which, can be found here.

For additional info please visit knockoutJS website

We will also need routing engine. Two libraries were considered:, sammyJS and pathJS. And of course the jQuery Mobile framework to get the mobile look & feel. So, we end up with the following:

  • jQuery Mobile
  • knockoutJS
  • pathJS
  • external template engine

After trial and error I was able to create a small SPA example using all of this component.

There are good MVC client side frameworks for SPA like backbone or ember. I did not try to reinvent the wheel. The purpose of this example was to check if we can use simple matured libraries we already use on daily basis in order to create simple SPA without suffering from high learning curve which exists in other frameworks.

The full example is included in the following git.

Thursday, November 29, 2012

MongoDB–NoSQL database

Lately I’ve been hearing a lot about so called NoSQL databases, Google has one, the BigTable. These databases are highly optimized for retrieving and saving data. They do not use SQL-like languages for data manipulation, and save data not in tables but in collections under key:value objects.

When writing rich client web applications you often find yourself moving data from the database through server side and to the client while serializing and converting the data to JSON in the process. Because of this the idea of a database that will save data as objects and will on start deliver the data to you in JSON seems very appealing.

After little research on this topic I’ve found the MongoDB database that can be found here. This database is used by number of companies e.g. SAP, Disney, Github, and many others. So, I’ve decided to take it to a test drive.

Installation

So, first of all we need to download the MongoDB from the website. There is not installation, just a zip file that should be extracted into a directory of your choice.

Inside MongoDB\bin directory you will find two files of interest, the mongod.exe and mongo.exe files. mongod file is the one we will use to startup the server, mongo file will is a console to run commands against the server. By default MongoDB will try to save all the databases into c:\data\db directory. If this directory does not exist mongod will fail to start unless we will create it or specify another directory where to save the databases.

To start MongoDB with specific save directory the following command should be initiated:

mongod –dbpath <directory>

After this, the following lines should be displayed:

image

You can also start MongoDB as a windows service. The following command line should be initiated:
mongod –install do not forget to add –dbpath if needed

Actually this is it, we have just installed and started a MongoDB server. Now we can start mongo.exe to run script commands on the database. We can also open web browser and navigate to localhost:28017 to be able see web adminsitration window:

image

Giving it a try

When we start the mongo console it will by default connect to test database, the database does not yet exist, it will be created when we save our first data in some collection. It is important to note, MongoDB does not have tables, it has collections instead. Instead of rows it has documents (objects). To save data we should run the save function on collection of our choice and pass a json object to it. For example, if we need to add a person with it’s first and last name to people collection it should look like this:

image

Now, to get all the documents from a collection we should run find function:

image

You can see we received the object we added to people collection and with it can back an _id field. This field was given to the document by the MongoDB and it represents a unique ID. If we would try to imagine how this function would look in SQL it should look like this:

SELECT * FROM People

You can get documents from collection on condition, for example:

db.people.find({firstName:”Israel”})

will be equals to

SELECT * FROM People WHERE firstName = ‘israel’

And of course you can get only part of the members in documents like so:

db.prople.find({}, {firstName:true})

is as same as

SELECT firstName FROM People

Last but not least for this post: we are free to change database whenever we want, for this we should run the use <database> command. Again, if the database does not yet exist it will not be created right away, it will be created when we save command.

Other options for the console can be printed out if you initiate help command

Conclusion

No-SQL database seems as a great and easy way to save and administer large amounts of data and then retrieve them as object right from the database. At MongoDB website you can find some of the user cases when you should consider using a No-SQL database, page can be found here.

There is also MongoDB ports for various programming languages that can be found here.

Wednesday, November 28, 2012

jQuery.inputFilter

Just wrote small jQuery plugin to filter text inside inputs. The plugin will limit characters input for the option chosen. The following options are available:
jQuery.inputFilter{{
    type: 'onlyNumbers|onlyEnglish'
});
onlyNumbers options is a default.

Plugin available here:
https://github.com/dimkinv/jQuery.inputFilter

Tuesday, November 20, 2012

Manage you application JS code with “namespaces”

For a while now I get to write rich JS applications. Some of the are small, others are pretty big. With the rising amount of JavaScript code there is a need to organize to be able to navigate there later.
There are some ideas for how to make JS to be roughly O.O language. There are the revealing model pattern, the prototype pattern and some others.
But, I find that except using these patterns there are the need to organize your JS code into namespaces or maybe so called “sections”, these should be intuitive, so let’s say for example you need to execute valid email function the JS code should look like this:
var isValid = myApplication.validations.validateEmail(validationFiled);
You can see here I’ve created a global “namespace” for the application, a validation “namespace” and inside these all the validations are defined, thus, whenever I want to validate something I know exactly where to look, and with the help of advance IDE like Visual Studio/Eclipse I can even get an intellisense.

And now the code itself. In JS you can define an array and use it in two different ways.

First way:

var someArray = [];
someArray[0] = 'someValue';
someArray[1] = 'anotherValue';

The second way:

var someArray = [];
someArray.someMember = 'somevalue';
someArray.someOtherMemebr = 'othervalue';
you can see that the second way may look like something we need. So, as we did with our someArray variable we can also make the variables inside arrays and add some more variables (or functions) to them.

How I do it:

Now for how I use to do it in my projects. You do not have to make exactly as I do, this is only an idea. Your needs may be different than mine.

I start with declaring the global scope namespaces and the sub-modules:
var myApplication = [];

//Here, the constant urls will be held (for example, the AJAX urls to contact my server from JS)
myApplication.urls = []

//Some constant variables can go here to be available everywhere.
myApplication.consts = [];

//Global functions you may have (converters, some global calculations, etc...)
myApplication.functions = [];

//Any validation functions you may have
myApplication.validations = [];

//I sometimes define resources inside JS for better response, it could be a "dictionary" object or an array 
myApplication.resources = [];

//I often work with knockout.js inside my projects, I use the following namespace for any models I may have. 
myApplication.models = [];
After declaring the global scope I usually declare some base information and functional data:
//Most of the application will have a modal dialog window to display messages these two functions are used to show and hide this dialog
myApplication.functions.showModalDialog = function(title, content, options){
};
myApplication.functions.hideModalDialog = function(){
};

//This string will define the base url for different url paths of my project 
myApplication.urls.ajax = 'localhost:8888/myApp/ajax';
myApplications.urls.root = 'localhost:8888/myApp';
It is extremely important to keep your JavaScript code in order. You should also consider using the patterns I’ve mentioned earlier.

I will try to post the O.O principles on my next post in this blog.

P.S

New blog, and first post.
I will be glad for every comment, correction, idea, note on this post. Be merciful on this one though :)