Showing posts with label O.O JavaScript. Show all posts
Showing posts with label O.O JavaScript. Show all posts

Sunday, August 18, 2013

Angular.js example from usergroup

Introduction

At 19/08/13 I've spoke at Gil Fink  UserGroup at Sela about introduction to Angular.js. Below a short overview of the example app presented.

Structure

When building Angular application is is most important to divide it into modules. The current example was relatively small so the modules division was made by different components of the framework (e.g. controller, services, filters, etc..). 
Note, that if the application is large and complex the division to modules should be made by features rather than by components. Each module should then contain everything related to the feature. It will allow us to take the feature to another Angular project with ease.

Please note, there are 5 examples in the main directory from the most basic to the most complex, I'll overview the last as it includes all the other examples as well

Bootstrapping

As an entry point I have the application.js file which defines all the modules available for the projects including the dependencies between them.

window.directives = angular.module('directives', [], function () {
});
window.services = angular.module('services', [], function () {
});
window.filters = angular.module('filters', [], function () {
});

Right after that, the main module configures the routes.

window.application = angular.module('myMovies', 
    ['directives', 'services', 'filters'], function ($routeProvider) {
    $routeProvider
        .when('/', {
            controller: 'mainCtrl',
            templateUrl: 'templates/movies_list_view.html'
        })
        .when('/about', {
            templateUrl: 'templates/about_view.html'
        })
        .when('/movieDetail/:id', {
            controller: 'movieDetailController',
            templateUrl: 'templates/movie_detail_view.html'
        })
        .otherwise({
            templateUrl:'templates/404.html'
        })
});

The $routeProvider has two functions. when - used to declare a valid route either with or without parameters and otherwise - will redirect at any illegal route entered.

Controllers

Two controllers are available one for displaying the movies on the main page and the other for displaying additional details about a movie
The mainController requests the mockService to get the movies data, and also defines event to remove movie on click.
The movieDetailController uses the same service to get movie by id. Note, the movie id is passed as a parameter in url (not as querystring). The controller then reads the parameter with the $routeParams provider.

Services

One service is available. the mockService gets it's data statically from another js file with timeout to simulate a delay.
Because I used timeout function there I need to call $scope.$apply() inside controller to notify Angular about changes to the data. 

        $scope.$apply(function () {
            $scope.model = {
                movie: movie
            }
        });

Normally, when fetching data from server we should use $http service to get the data, the $http service will take care for notifying about changes

Filters

Build-in filters are used in movies list template to filter movie results by the search field. Also, one custom filter is available to convert minutes to more visualisable format.

Templates

Templates for every page is available and are loaded when route gets resolved. Also 404 template is available for the 'otherwise' function.

Conclusion

To create this example I've simplified the structure of the project. The file structure should be a bit different and I hope that soon I'll post a full project example showing the structure as I see it. 
I also simplified the code for the sake of this example, so probably it won't look 100% the same in real life project.

The code examples are available here: http://goo.gl/1xlQFS

I'll be glad for every input you may have about this post or the examples. 

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 :)