Sunday, April 7, 2013

TodoMVC using Mojito, Part 2: Common affinity controller

In Part 1, we got our basic application ready with the following setup:
  • Application and Routing Configuration
  • TodoMVC defined assets
  • Initial UI - HTML markup and CSS stylesheet
In Part 2, we explore configuring all of the CRUD actions and update all associated artifacts - model, controller and binder. Specifically, we explore the following actions - one at a time:
  1. Action – List all TODOs
  2. Action – Add a TODO
  3. Action – Edit a TODO
  4. Action – Mark one or all complete
  5. Action – Delete a TODO

Step 1: Action - List all TODOs

The first thing that we build up is retrieving all TODO items and showing them up. If there are no items in the list, then, as per the specs, the #main element must be hidden.
Let us start with updating the model followed by the controller and binder in that order.

Updating the model

We add a function getAll. Though, in our case, the storage is simple and synchronous, I would rather prefer to write the method in the manner preferred in asynchronous systems. The method requires no inputs to process. As such, our function takes exactly one parameter - a callback function to be invoked to return the result - failure or success.

Below is the code for the function:

[code lang="js" highlight="14,15-22" title="todo.common.js"]
YUI.add('TodoMojitModelTodo', function(Y, NAME) {
  var storage = new Y.CacheOffline();

  Y.namespace('mojito.models').Todo = {
    init: function(config) {
      this.config = config;

      var initData = storage.retrieve('todo');
      if(!initData) {
        storage.add('todo', []);
      }
    },

    getAll: function(callback) {
      if(storage) {
        var obj = storage.retrieve('todo'),
            rv = obj.response;
        callback(null, rv);
      } else {
        callback('Storage not initialized');
      }
    }
  }
}, "0.0.1", { requires: [ 'json', 'cache-offline' ] });
[/code]

There are two ways to cook-up the controller:
  • One, create an action, say, operate, that is implemented using command pattern.
  • Two, create multiple actions, one for each operation.
The first style is what I have used in my actual code. For the sake of completeness and variety, I use the second option here. So, let us create a function getAll in the controller as well. Additionally, we create another view - items.hb.html - that will be used to

[code lang="js" title="controller.common.js" highlight="13-22,23"]
YUI.add('TodoMojit', function(Y, NAME) {
  "use strict";

  Y.namespace('mojito.controllers')[NAME] = {

    index: function(ac) {
      ac.assets.addBlob('<meta charset="utf-8">\n<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">', 'top');
      ac.assets.addBlob('<link href="/static/' + ac.type + '/assets/base.css" rel="stylesheet" type="text/css" />', 'top');
      ac.assets.addBlob('<!--[if IE]>\n<script src="/static/' + ac.type + '/assets/ie.js"></script>\n<![endif]-->', 'top');
      ac.done({});
    },

    getAll: function(ac) {
      ac.models.get('Todo').getAll(function(err, items) {
        if(err) {
          ac.error(err);
        } else {
          ac.done({
            "items": items.reverse()
          }, 'items');
        }
      });
    }
  }
},  '0.0.1', {requires: ['mojito', 'TodoMojitModelTodo',
   'mojito-models-addon',  'json',
   'mojito-assets-addon', 'mojito-params-addon']});
[/code]

And here's how our view looks like:

[code lang="html" title="views/items.hb.html"]
{{#items}}

<li id="{{id}}" class="{{#completed}}completed{{/completed}}">

<div class="view">
 <input class="toggle" type="checkbox"{{#completed}} checked="checked"{{/completed}} />
 <label>{{{title}}}</label>
 <button class="destroy"></button>
</div>

<input class="edit" type="text" value="{{{title}}}" />
</li>

{{/items}}
[/code]

To glue it all, we need the binder. The binder, upon launch, will request to get all the items and update the UI. We create two functions in the binder:
  • resync: This function will fetch the markup for all the items and trigger UI refresh.
  • _resyncUI: This function will actually refresh the UI.
[code lang="js" title="binders/index.js" highlight="19,22-33,35-50" firstline="10"]
      bind: function(node) {
        var self = this;

        this.node = node;
        this.inputNode = node.one('#new-todo');
        this.listNode = node.one('#todo-list');
        this.toggleAll = node.one('#toggle-all');
        this.main = node.one('#main');

        self.resync();
    },

    resync: function() {
      var self = this;
      self.mp.invoke('getAll', { 'params': { }}, function(err, response) {
        if(!err) {
          self.listNode.set('innerHTML', '');
          if(response) {
            self.listNode.append(response);
          }
          self._resyncUI();
        }
      });
    },

    _resyncUI: function() {
      var n = this.node,
        toggles = n.all('.toggle'),
        size = toggles.size(),
        allSel = true,
        i;

      for(i = 0; i < size; i++) {
        if(!toggles.item(i).get('checked')) {
          allSel = false; break;
        }
      }
      this.toggleAll.set('checked', size > 0 ? allSel : false);
      this.main[size > 0 ? 'show': 'hide']();
    }

  };

}, '0.0.1', {requires: ['mojito-client', 'node', 'json', 'escape']});
[/code]

Launch the application. It should, still, show same UI as earlier. There are no TODO items after all.

Monitor the console (Firebug or Chrome console) to ensure that there are no errors. Firebug console should show you log similar to as shown next:



In the next post, we implement the add behaviour to our application.

Friday, April 5, 2013

TodoMVC using Mojito, Part 1: Common affinity controller

This is first post in the series that describes building a simple Todo application using Mojito. The constraint that we have in our first implementation is that the controller will have common affinity.
As a prerequisite to understanding the implementation, I would assume that you are well versed with JavaScript and are hands on with Mojito. If not, it may be worthwhile to explore my initial posts on getting started with Mojito.

The complete code generated can be structured in the following steps:
  1. Initial code generation using Mojito CLI tools
  2. Application and routes configuration
  3. Initial UI - View and CSS
  4. Model
  5. Controller
  6. Binder
  7. Action - List all TODOs
  8. Action - Add a TODO
  9. Action - Edit a TODO
  10. Action - Mark one or all complete
  11. Action - Delete a TODO

Step 1: Initial Code generation using Mojito CLI Tools

We start by creating a Mojito application - todomvc, and adding a mojit, TodoMojit. The steps are pretty simple:

[code lang="bash"]
$ mojito create app todomvc
$ cd todomvc
$ mojito create mojit TodoMojit
[/code]

Step 2: Application and routes configuration

The next step is to update application.json and routes.json files.

Application configuration file is updated for the following changes:
  • staticHandling section for application name
  • specs section to register the mojit
[code lang="js" highlight="6-12,15-17"]
[
  {
    "settings": [ "master" ],
    "appPort": 8666,
    "specs": {
      "main_ui": {
        "type": "HTMLFrameMojit",
        "config": {
          "deploy": true,
          "title": "Yahoo! Mojito • TodoMVC",
          "child": { "type": "TodoMojit" }
        }
      }
    },
    "staticHandling": {
      "appName": "todomvc"
    },
    {
      "settings": [ "environment:development" ],
      "staticHandling": {
        "forceUpdate": true
      }
    }
]
[/code]

Routes configuration file is updated for:
  • Mapping the index action of the controller to / path.
[code lang="js" highlight="3-6,7"]
[{
  "settings": [ "master" ],
    "root": {
      "path": "/",
      "verbs": [ "get" ],
      "call": "main_ui.index"
    }
}]
[/code]

Step 3: Initial UI - View and CSS

Now that we can access our application at http://localhost:8666, it is time to make initial user interface - the view and CSS.

We will require the following existing artifacts from TodoMVC project:
Copy all these files to mojits/TodoMojit/assets folder.

Open mojits/TodoMojit/views/index.hb.html and update it using the template provided in the TodoMVC project at https://github.com/addyosmani/todomvc/blob/gh-pages/template/index.html.

There is, however, one catch with it. We will not use it as is. Notice that this is complete HTML where as in our case, the page chrome is emitted by HTMLFrameMojit. Also because Mojito does not provide any client-side routing by itself, we need to remove that section as well.

Essentially, what we are left with it bare-bone view that comprises of the header, main and info sections. Our final index.hb.html looks as below:

[code lang="html"]
<div id="{{mojit_view_id}}">
    <section id="todoapp">
  <header id="header">
   <h1>todos</h1>
   <input id="new-todo" placeholder="What needs to be done?" autofocus>
  </header>
  <section id="main">
   <input id="toggle-all" type="checkbox">
   <label for="toggle-all">Mark all as complete</label>
   <ul id="todo-list"></ul>
  </section>
 </section>
 <div id="info">
  <p>Double-click to edit a todo</p>
        <p>Created by
          <a href="https://github.com/gvaish">Gaurav Vaish</a>
        </p>
  <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
 </div>
</div>
[/code]

Delete mojits/TodoMojit/assets/index.css - auto-generated file.

At this time, if you run the application, the UI will be as shown next:

Step 4: Model

Now that we have basic UI in place, it is time to look at our model. Delete the auto-generated model at mojits/TodoMojit/models/foo.server.js and create a file mojits/TodoMojit/models/todo.common.js. The model affinity is common in sync with our main restriction.

We will use CacheOffline as the store to persist the todo-items. This makes use of localStorage in the browsers where available.

The initial code of the model look as below:

[code lang="js"]
YUI.add('TodoMojitModelTodo', function(Y, NAME) {

  var storage = new Y.CacheOffline();

  Y.namespace('mojito.models').Todo = {
    init: function(config) {
      Y.log('Initializing... ', 'info', NAME);
      this.config = config;

      var initData = storage.retrieve('todo');
      if(!initData) {
        storage.add('todo', []);
      }
    }
}, "0.0.1", { requires: [ 'json', 'cache-offline' ] });
[/code]

All that this piece of code does is initialize the storage and ensure that it contains an empty list of todo items.

At this point in time, the application is in an erroneous state because the model used in controller is no longer available.

Step 5: Controller

Couple of things that are seriously broken are stylesheets and model. Firstly, though we added the files, we do not refer to them in final UI. Secondly, the controller needs to access the new model definition.

To inject the css and js files in the final output, we make use of the addBlob method of the assets addon. Additionally, we rename controller.server.js -> controller.common.js as per our constraint.

Change the file contents to as below:

[code lang="js" highlight="2,7-10,13-15"]
YUI.add('TodoMojit', function(Y, NAME) {
  "use strict";

  Y.namespace('mojito.controllers')[NAME] = {

    index: function(ac) {
        ac.assets.addBlob('<meta charset="utf-8">\n<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">', 'top');
        ac.assets.addBlob('<link href="/static/' + ac.type + '/assets/base.css" rel="stylesheet" type="text/css" />', 'top');
        ac.assets.addBlob('<!--[if IE]>\n<script src="/static/' + ac.type + '/assets/ie.js"></script>\n<![endif]-->', 'top');
        ac.done({});
    }
  }
},  '0.0.1', {requires: ['mojito', 'TodoMojitModelTodo',
     'mojito-models-addon',  'json',
     'mojito-assets-addon', 'mojito-params-addon']});
[/code]

Analyzing what we have done is:
  1. Writing in strict mode - a requirement of the TodoMVC project.
  2. Added HTML-blob in the head section of the HTML page.
We need to do #2 above because because that how the HTMLFrameMojit allows you to inject meta and other HTML. Line 8 above is not necessary - we can configure that part using application.json configuration as well. For the sake of keeping code at one place, I choose controller.

Start the application again. Because we have styles in place, we expect an enhanced UI as shown below.

Step 6: Binder

Binder is the client-side component that runs in browser and provides the glue between the UI/events and controller. The default binder code can be found at mojits/TodoMojit/binders/index.js.

Binder has strictly two methods that are invoked by the Mojito client runtime:
  1. init - called before DOM is setup. This method is passed a reference to proxy-object for the mojit.
  2. bind - called after DOM is setup. This method is passed a reference to the Node from the view rendered. It is required that the view must have one top-level element and either this or one of the child nodes has id of {{mojit_view_id}}.
Update the code of the binder to as follows:

[code lang="js" highlight="4,8,10-14,19"]
YUI.add('TodoMojitBinderIndex', function(Y, NAME) {
  Y.namespace('mojito.binders')[NAME] = {
    init: function(mojitProxy) {
      this.mp = mojitProxy;
    },

    bind: function(node) {
      var self = this;

      this.node = node;
      this.inputNode = node.one('#new-todo');
      this.listNode = node.one('#todo-list');
      this.toggleAll = node.one('#toggle-all');
      this.main = node.one('#main');
    }

  };

}, '0.0.1', {requires: ['mojito-client', 'node', 'json', 'escape']});
[/code]

The changes are described below:
  • Line 4: Shortened the variable name to mp.
  • Line 10-14: Cache important items - root node for the UI-container, input node, list-container, list and toggle check-box.
  • Line 19: Added dependencies as we need to HTML-escape any input and our data model to communicate will be JSON.



At this point, we have initial view of our application ready. I will put up the code for the next set of steps - the crux, the actions - in next post.

Wednesday, April 3, 2013

Todo MVC using Mojito

TodoMVC is an awesome project by Addy Osmani and Sindre Sorhus. In their own words:
Developers these days are spoiled with choice when it comes to selecting an MV* framework for structuring and organizing their JavaScript web apps.
Backbone, Ember, AngularJS, Spine... the list of new and stable solutions continues to grow, but just how do you decide on which to use in a sea of so many options?
To help solve this problem, we created TodoMVC - a project which offers the same Todo application implemented using MV* concepts in most of the popular JavaScript MV* frameworks of today.
The website now boasts of implementations using over three dozen frameworks. And I decided to pitch in using Mojito by Yahoo!


The main code is available at https://github.com/gvaish/todomvc-mojito. I intend to implement with the following four variants:
  • Using controller with common affinity, so that all execution happens on the client side once loaded.
  • Using controller with server affinity, to be able to describe a scenario on how one can shift execution from client to server.
  • Using YUI App framework, to show one can migrate an existing YUI application to Mojito
  • Using jQuery, to demonstrate how cool and easy it is to inter-operate the two.
The next couple of posts will be dissecting the Mojito TodoMVC application with common affinity for the controller, followed by migration to server affinity. The rest will follow soon.

Tuesday, April 2, 2013

Book: Getting Started with NoSQL

After a few months of authoring, exchanging mails with the publisher on the final content and reviews, and exchanging mails with Satish - lead reviewer, my book - Getting Started with NoSQL (ISBN: 9781849694988) - is finally out in the market.



The book is available on Amazon at:
A bit in detail about the book:
Relational databases have been used for decades, and in the last few years NoSQL has been a growing choice for large-scale web applications. Non-relational databases provide the scale and speed that you may need for your application. To switch you must know the options available, the advantages and drawbacks, and scenarios which it is suited to the most and where it should be avoided at all costs. 
Getting Started with NoSQL is a from-the-ground up guide that takes you from the very first steps to a real-world NoSQL application. It provides you with a step-by-step approach to design and implement a NoSQL application that will help you make clear decisions on database choices and database model choices. The book is suited for a developer, an architect, as well as a CTO. 
This book is a comprehensive guide to working with NoSQL. You will learn to make key decisions, and to design and implement NoSQL applications. You will learn about NoSQL jargon, data models, and databases on the market. The case studies and comparisons presented will help you to make a decision on whether or not to use NoSQL, and if so which model and product to use. This book is an indispensable resource for you to have in your library. You will learn everything you need to know about understanding and working with NoSQL and how to implement an application with the correct NoSQL for you.

Friday, February 8, 2013

Writing Files to GAE Blobstore

FileSystem API was introduced in AppEngine last year. A great feature. I tried using it more than a couple of times and ended up with one problem or the other. Some of the notable issues include:
  • What should be the filename during create and save? The name given during create was only name-part and cannot be used during read. Read must use fullpath.
  • If you use fullpath, you cannot use it to delete the file.
After a bunch of experiments, I concluded that it is best to use BlobKey.


As a contribution, I have published the code that would help you out working with the low-level API at Github - https://github.com/gvaish/gae-utils/. The actual class - BlobstoreFS - is available here.

The following methods are available:
  • save: To save contents to a file. You can either provide BlobKey of an existing file if you wish to overwrite the contents.
  • delete: Delete the file, along with the associated BlobKey.
  • open: Gives you InputStream for you to be able to read the raw contents
  • readToEnd: Returns String containing the file contents.