Sunday, May 27, 2012

Yahoo! Mojito: Part 1 - Hello World!

Yahoo! Mojito is, now, watched officially by 1027 developers (as of writing this article) on Github (see https://github.com/yahoo/mojito/watchers) and is actively contributed by developers across the board (see https://github.com/yahoo/mojito/network). And I'm pretty sure, there will be several others who would have downloaded, installed and tried.

Before getting into this detailed Hell World tutorial, I assume that you've already installed Yahoo! Mojito using the instructions given at https://github.com/yahoo/mojito README. I preferred an npm-install to ensure that I get a stable version.

Defining the "Hello World" application:
  1. The first step will be to create an application with defaults, no customization, and get it running.
  2. Next, we'll make the application run at port 80 and ensure that the content is available at "/" rather than a strange but intuitive default path.
  3. Subsequently, we'll change the default contents to reflect "Hello World" in the message
  4. And finally, we'll make the application interactive by creating a simple form that will accept user's name and say hello to him/her rather than to the whole world ;)
And here's some vocabulary before we deep dive:
  1. Yahoo! Mojito: MVC framework for JavaScript based application.
  2. Mojito Application: An application based on Mojito framework.
  3. Mojit: A mojito widget - with its own model, view, controller and binder.
We call this application - "HelloWorldApp" and the mojit as "HelloMojit".

1. Creating application with defaults:

[code lang="bash"]
$ mojito create app HelloWorldApp
$ cd HelloWorldApp
$ mojito create mojit HelloMojit
$ cd ..
[/code]

At this point in time, we have the skeleton of the code ready. Let's just have a brief look at the artifacts created:


The main configuration file is application.json that defines the application structure, specifically, the mojits and their configuration, application name, port number etc.

If you open the file in an editor, the contents will be as follows:

[code lang="js"]
[
    {
        "settings": [ "master" ],
        "specs": {}
    }
]
[/code]

What this says is that there is one setting named "master" (default settings to be loaded by Mojito runtime) with empty specs.

We need to tell Mojito that we have a mojit - HelloMojit - and it should pick up most of things on its own. Update the contents of the file to as below:

[code lang="js"]
[
    {
        "settings": [ "master" ],
        "specs": {
            "hello_mojit": {
                "type": "HelloMojit"
            }
        }
    }
]
[/code]

The updated content tells Mojito runtime that there is a mojit referred to as "hello_mojit" and its underlying type is "HelloMojit". What exactly does it mean I'll detail later... we're ready with the baseline of our application. It's time to start the server. Issue the command:

[code lang="bash" light="true"]
$ mojito start
[/code]

Launch your browser and point it to http://localhost:8666, 8666 being the default port on which the mojito server runs.

Well, very interestingly but probably not surprisingly, we get a 404:


That's quite understandable as Mojito does not now know what to show at the root path. But what it does know is about the HelloMojit mojit. So, let us now point the browser to http://localhost:8666/@HelloMojit/index. It means point to the HelloMojit and execute the action index, and now you should get


You can also browse to http://localhost:8666/hello_mojit/index. And I don't think I should need to explain what "hello_mojit" means. If you don't remember, just look back into the contents of application.json.

2. Customize port and map at "/"

Now that we have the application running, let's make two changes - make it run on port 80 and ensure that we don't make life of our users hell by asking them to remember such a long URL.

application.json has a configuration named appPort with default value of 8666 unless specified otherwise. So, let's specify the otherwise. Update the contents to as follows:

[code lang="js"]
[
    {
        "settings": [ "master" ],
        "appPort": 80,
        "specs": {
            "hello_mojit": {
                "type": "HelloMojit"
            }
        }
    }
]
[/code]

And then, do a

[code lang="bash" light="true"]
$ sudo mojito start
[/code]

The sudo is required because the application will not run on port 80, and most Unix/Linux systems require admin/root privileges to run a server on ports below 1024.

Now, you can browse to http://localhost/@HelloMojit/index.

The next big thing to have the same content available at http://localhost rather than the otherwise obscure URL. The routing configuration resides in a separate routes.json file.

Why a separate file? Well, it definitely makes a sense to segregate the mojit-list and their access points.

So, let's update the routes.json file with the following content:

[code lang="js"]
[{
    "settings": [ "master" ],
    "root": {
        "path": "/",
        "verbs": [ "GET" ],
        "call": "hello_mojit.index"
    }
}]
[/code]

The content reads that for settings "master", if anyone access the path "/" (root) using the HTTP GET method, call the action index of hello_mojit registered in application.json.

Restart the server... and now you are ready to browse to http://localhost.

Having said that, if you try to browser to the earlier URL, you should get a 404. Mojito application is pre-configured to ensure that if you do have at least one route registered, direct access to any mojit will not be allowed - ensures accidental access.

3. The "Hello World" message

Now that we have the default application up and running at port 80 and root path, it's time to look at where the content of the website is coming from.

If you look into the mojits -> HelloMojit folder, you will find:
  • A file controller.server.js
  • A file views/index.mu.html
The controller has the business logic of working with the data, incoming request, application state and is responsible for providing the final data to be rendered by the view.

The view, in this case, is a mustache template (and hence the name index.mu.html) is fed the data by the controller for rendering.

Let us update the template (index.mu.html) to reflect the following:

[code lang="js" highlight="2"]
<div id="{{mojit_view_id}}">
   {{message}}
</div>
[/code]

and update the controller (controller.server.js) to the following:

[code lang="js" highlight="9"]
YUI.add('HelloMojit', function(Y, NAME) {
    Y.mojito.controllers[NAME] = {

        init: function(config) {
            this.config = config;
        },

        index: function(ac) {
            ac.done({ "message": "Hello World" });
        }

    };

}, '0.0.1', {requires: ['mojito', 'HelloMojitModelFoo']});
[/code]

Comments have been removed for brevity.

The template reads that it needs a key named "message" to be displayed.

The controller has an action index which reads I am done with my processing and the data to be used by the template has a key named "message" with a value "Hello World".

Restart your server, open the URL in the browser and you should see the following:

Hurray! We now have a "Hello World" application up and running. And while doing this, we learnt about the following:
  1. Create a new Mojito Application
  2. Create a mojit
  3. Register a mojit in application configuration file
  4. Configure / change the port number
  5. Configure route mapping
  6. View template of a mojit
  7. Basic configuration of controller to provide content for the view
Now it's time to go deeper - create a form, process incoming data and generate data for the output view.
Because that's going to be a long enough article in itself, I'll put this in my next post!

No comments:

Post a Comment