Pages

Sunday, 21 July 2013

MVC Architecture & Oops in JavaScript using PhoneGap

Introduction:

In this post, we'll look into the creation of MVC architecture in JavaScript. Using MVC in PhoneGap applications makes them modularize, which is much helpfull during big projects and most of all, makes them easy & simple to handle and review during maintenance. Use of Oops concept, helps us making multiple instances of Model/Controller that can be used with multiple views, each having it's own scope.

Description:

First of all, lets have a look into the MVC Architecture. As we know Model creates the bridge between the database and the Controller, where as View manages the UI in associate with the Controller. So, the vital part is the Controller, which builds the passage between the Model and View, passing the data to & fro. The Controller contains all the logical codes that need to be done, and rest Model & View just contains the code required to manipulate the data.

Below is the basic HTML we need for showing the list view.

        <div id="wrapper">
            <div id="scroller">
                <ul id="container"></ul>
            </div>
        </div>


Now we need to create the MVC Architecture, so we will be having the following files,

    RecipeModel.js - It will manage all the database queries.
    RecipeView.js - It will make the UI changes to show the Recipe List.
    RecipeController.js - It will manage the data flow between View and Model.
   
So let's have go through the Model,

    RecipeModel.js
    ------------------
   
    var RecipeModel = function() {
       
     // Code to open database and retrieve records
     // from it.
       
  };
   
Now it's the time to code for Controller, let's see how.

    RecipeController.js
    ------------------
   
    var RecipeController = function() {
       
    // Get the model object
    this.model = new RecipeModel();
       
    // Code to get the list of recipes from model
       
  };
   
And finally, we will go for creating the View,

    RecipeModel.js
    ------------------
   
    var RecipeView = function() {
       
     // Get the controller object
     this.controller = new RecipeController();
       
     // Code to loop through the array and print the

     // recipes to the html
       
  };
   
That's all, we can now have the list of recipes listed on the UI. For a detailed code and reference follow my post here

Summary:

    Using MVC makes the flow go simple and concrete, all together making it quite easy during maintenace.


No comments:

Post a Comment