App patterns

by ronilan

JavaScript

// external api
var googApi = {
    addressGeoCode: function (formattedAddress) {
        var url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + encodeURIComponent(formattedAddress) + "&sensor=false";
        return $.get(url);
    }
};


/** 
 * var app in global scope
 * call app.init();
 */

var app = {

    init: function () {

        /* code */
        console.log("app");

        dfd = googApi.addressGeoCode("1600 Amphitheatre Parkway Mountain View, CA 94043 ");

        dfd.fail(function () {
            $("#message").text("failed to get data :(");
        });

        dfd.done(function (obj) {
            $("#action").show();
            console.log("done", obj);
        });

    }

};


/** 
 * Create an anonymous Immediately-Invoked Function Expression (IIFE).
 * It that gets invoked immediately and return the API.
 * call Moduley.someMethod();
 */

var Moduley = (function () {

    // always invoked
    console.log("Moduley");

    dfd = googApi.addressGeoCode("1600 Amphitheatre Parkway Mountain View, CA 94043 ");

    dfd.fail(function () {
        $("#message").text("failed to get data :(");
    });

    dfd.done(function (obj) {
        $("#action").show();
        console.log("done", obj);
    });


    // private methods
    function _someMethod() {}

    // expose API
    return {
        someMethod: function () {
            _someMethod();
        }
    };

}());


/** 
 * Create Function.
 * It returns the API.
 * call:
 *   appy = new Appy();
 *   appy.init();
 */

function Appy() {

    /* code */
    console.log("Appy");

    function _init() {

        dfd = googApi.addressGeoCode("1600 Amphitheatre Parkway Mountain View, CA 94043 ");

        dfd.fail(function () {
            $("#message").text("failed to get data :(");
        });

        dfd.done(function (obj) {
            $("#action").show();
            console.log("done", obj);
        });

    }

    // expose API
    return {
        init: function () {
       ...