Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Tuesday, May 7, 2013

AngularJS Directives - building a DSL with your HTML

I will admit in advance - this content trades off of a great little screencast by Brian Ford from CODEShow on AngularJS directives. Go watch that if you have a little knowledge of AngularJS and 45 minutes to kill... But if not...

What is AngularJS?

Google built AngularJS, a Javascript MVC (well, MV VM, more later) to write single-page web applications. It provides an application framework, which lets you define view templates for your HTML content, register MVC controllers (for handling activities, listening for events and initializing views), build services (stateful or stateless Javascript code for handling integration to outside data sources and sinks), and several other components, including directives.
As I mentioned before, we'll get to directives in a bit. But first, the 5 minute AngularJS sample.

AngularJS in a nutshell

AngularJS provides a bridge between your HTML and Javascript via a nice two-way data-binding mechanism. Angular uses a view model object, which can be set within your controllers, to send data to a page. A one-way example:
To play with this, just click on the various headings (Javascript, HTML, Result). I'm using JSFiddle, an incredibly useful playground where you can quickly cook up snippets of whatever you wish and share them online, even associate them with your GitHub account.

Breakdown - the Module

you can see that we've defined an module named 'demo' (ignore those square brackets for now):
var demo = angular.module('demo', []);
This module defines an application for us. We can eventually register a number of elements in this application, but for now, we'll just set up the application itself so it can be bound to a portion of our page.

The Controller and 'ViewModel'

We then defined a controller called 'MyCtrl':
function MyCtrl($scope) {
...
}
which will automatically inject the magically named 'scope' variable - $scope. Just like Spring or other dependency injection systems, provided you know the service you're injecting, you specify it by name. Built-in and add-on services from Angular generally use the '$' prefix. Yours will not. That's a way of distinguishing user code from system-built code.
The '$scope' variable is a ViewModel - meaning a model specific to display of a template or view. To demystify the whole 'MVVM' term you may have heard, consider the ViewModel is simply the model that is given to the view, so that you can decouple it from your application's internal model, some of which you may not want to share with the page at a given time. Those darn terms...

The View

Now we come to the view. In our case, we've decided to make this view static - meaning that it's embedded into the page. We can certainly set up external views in another post, but for now, let's just focus on the content. You'll notice in the HTML we've defined two special tag attributes that you won't recognize, 'ng-app' and 'ng-controller'.

Greeting

Hi, it's Ken. The current time is {{time}}.
The ng-controller attribute is easy - it tells the page to watch for any data exported from our controller, named MyCtrl, and inject data stored in the $scope variable by its name. You'll notice above we left out our controller implementation. Let's look at it now:
function MyCtrl ($scope) {
    $scope.time = new Date().toTimeString();
}
Now, you can see the linkage - the $scope.time variable becomes {{time}} in the page. But what about the ng-app attribute?

The ng-app attribute defines what the scope of a given application might be on a given page. Like the controller, this limits the exposure of the application to a given area of the page. An application may be composed of elements such as controllers, services, views, directives, etc., and you may have need of Angular on several completely unrelated places on a given page. That's OK, you can create two applications, or an outer application and two related inner applications, all by defining modules. Further, once you start building components you'll likely want to set up more than one controller on a given view page, rather than one monolithic controller and view.

A sample directive

Ok, so let's bring it home. Maybe we want to think of the time as a 'feature' - something we'd use on the page in a few places. What if we wanted it to be referred to by a 'display-current-time' HTML tag? Something like this:
Hi, it's Ken. The current time is
to define a tag like that, you use a directive - a Javascript component that provides an HTML tag, attribute or CSS class with YOUR defined name, that then behaves like a DSL language element in the page.

Defining a directive

Let's begin with what we want our HTML to look like. This is a completely trivial and silly example, but it gives you an idea of what you can do.

Greeting

Hi, it's {{name}}. The current time is .
I didn't want to remove the controller, so I used it to bind the name to 'Ken'. Here's the controller now:
function MyCtrl ($scope) {
    $scope.name = 'Ken';       
}
Ok, our manager is going to freak out. Maybe later we'll externalize this into a form field, and show you that nifty two-way binding.

The directive

Now for the directive. We'll add it to the javascript sample file, and since we've defined our application (demo) above, we simply add the directive to it.
demo.directive('displayCurrentTime', function() {
    return {
        restrict: 'E',
        template: '12:00:03'
    };
});
The directive is given a camel-cased name - displayCurrentTime and in the inimitable Javascript way, we provide the implementation as an inlined anonymous function. The directive must return at least a template to render, and optionally a narrowed-down 'restrict' variable which tells Angular to activate the directive for HTML tags/elements (E), HTML tag attributes (A), or CSS classes 'C'. In the example above, we're going to only activate it for tags.
Angular expects that camel-cased name to turn into a lower-cased, dash-separated name in the HTML. Hence why our tags above are called 'display-current-time'.

Getting dynamic

Now let's get a bit more code-driven and dynamically generate the time.
demo.directive('displayTime', function($parse) {
    return {
        restrict: 'E',
        replace: true,
        transclude: false,
        template: '',
        link: function (scope, element, attrs, controller) {
            var currentDate = new Date();
            element.text(currentDate.toTimeString());
        }
    }});
One key function of a directive is to link the content in the model to DOM elements on the page. We supply a link function definition, and AngularJS injects the element as the second parameter. We then create a Javascript date with an empty constructor (current time) and use the element's text method to send it to the content of the span itself. In more advanced cases, we can supply a compile method, which is more powerful, but for simple cases like this the link method will suffice. Play with this snippet: By the way, if you begin trying to troubleshoot issues with your AngularJS or other framework app, some developers insist you reproduce the core problem in a tool like JSFiddle. It's a good way to play with a sandbox with zero setup.

Marco... Polo!

Let's take this one step further, and implement another directive to provide a business-level component. Perhaps you need to provide a list of user roles in a drop-down element, and you want to notify the rest of the application when you've changed the current one. In AngularJS, a typical way to do this is via a controller and view:

Play around with the values, and open Firebug or your Chrome developer tools (sorry IE users, I'm sure there's a way but I've been a mac user for too long). You'll see the console writing the change as we make it. Note the name of the attributes all begin with ng-. That's short for Angular. These are built-in attributes of the various supported widgets. Read up on the various ngXXX API attributes/elements to learn how to control text boxes, buttons, text areas, and other objects.

The DSL for groups

Let's say you want to set up a widget for group selection, with its own styling and form elements. You might start by coding it directly using a controller/view combination. First, we're using a simple form, with some AngularJS decoration here. From the HTML:
    <form class="userGroup">
        <label for="userGroupSelect">Select a Group</label>
        <select 
            ng-model="currentGroup"
            ng-options="o.value as o.label for o in myGroups"></select>        
        <input type="button" ng-click="applyNewGroup(currentGroup)" value="Switch Group"/>
    </form> 
Now, we'll bring in the AngularJS controller. We'll break this down step-by-step. First, we provide the application and a controller:
var demo = angular.module('demo', []);

function MyCtrl ($scope, $rootScope) {
    $scope.myGroups = [
        {label:'Admin', value:1},
        {label:'Users', value:2},
        {label:'Public', value:3}
    ];
    ...
}
The group list is arbitrary here - we could easily use Angular's $http component or even a RESTful resource to fetch the values. Note that the myGroups scope variable lines up with the curious expression in the ng-options attribute of our select tag. Let's explain that:
o.value as o.label for o in myGroups
What? Ok, this is almost like a select statement. It's one of the things in Angular you have to read through a few times to get it right. This expression assumes we are passing it an array of JS objects (myGroups) and that we're providing both a display and an option for the option tag it generates. Reading the fragments from the right, we first assign an alias 'o' to myGroups (o in myGroups). Then, we provide an optional label in the middle (o.label), and the data value (o.value). Hence, 'o.value as o.label for o in myGroups'. Easy, peasy? Well, nope but it does work. See the select directive and the cries for better documentation in the comments to make sure you're not the only crazy one.

Handling the change event

Rather than immediately changing the group for our application, we want to do it once the user clicks the button. So in that way, our currentGroup model element is transient. To do that, we'll define a function that takes the immediately bound model element currentGroup and broadcasts it to the rest of the application:
$scope.applyNewGroup = function (currentGroup) {
    $rootScope.$broadcast("new group", currentGroup);
};

// this could be anywhere in our application...
$scope.$on("new group", function(obj, value) {
    console.log("Global group switched to " + JSON.stringify(value));
});
You may not have noticed but in our controller, we not only requested $scope, but $rootScope. The root scope is a scope that all controllers in our application can see. If we wanted our controllers to be notified when the user changes groups, we simply call the root scope's $broadcast method, passing it a message and optionally, data to send. We've done that by passing the group id along. To subscribe to a message, in any sub-scope of the application (any controller), we just use the local scope's $on method. The scope is passed the object generating the event and the value passed. Since the value is our group, we accept it.

Put it all together

Now we'll put in the magic sauce. Let's externalize the form into a template string (yes, this can be an URL instead and loaded as a view file) and use the directive function to set it up:
demo.directive('userGroupSwitcher', function() {
    return {
        restrict: 'E',
        replace: true,
        transclude: false,
        template: '<form class="userGroup">
         <label for="userGroupSelect">Select a Group</label>
         <select ng-model="currentGroup" 
           ng-options="o.value as o.label for o in myGroups" />
         <input type="button" 
            ng-click="applyNewGroup(currentGroup)" 
            value="Switch Group"/>
         </form>'
    };
});
Then, to place the tag on the screen, we use:
    <user-group-switcher />
Play around with it here:

Summary

AngularJS is a powerful client-side Javascript application platform. You can use as little or as much of it as you wish. There are tons of samples online about building Angular web applications with simple controllers and forms, but I wanted to show you how to write directives - a way of liberating your domain-specific features from DOM elements, and allowing you to assemble views using business-specific building blocks. You can use directives for anything from menus, to re-use of forms, to wrapping other JS component libraries and widgets, to anything you can think of. Combining directives with Angular's message passing, easy REST/Ajax support, two-way data binding, support for templates and dependency injection, it's hard to pick a better framework (in my opinion) that can get you started quicker or provide you more flexibility without forcing you to build your own skeleton.

Resources

For finding more AngularJS component libraries based on directives, see ngmodules.org. A few of my favorites: Angular Bootstrap, for wrapping / encapsulating Twitter bootstrap features using directive tags and attributes, Angular UI, a set of widgets based on jQuery UI, and one I'm hacking with right now, jQuery Mobile Angular Adapter which tries to settle the score between Angular's dynamic views and jQuery Mobile's jump-link based dialog switching. For hacking around with Angular, please DO use JS Fiddle and search around for some good ones to start from. Feel free to fork any of mine to get going. In my next article, I'll show you more of the inner workings of Angular directives. If you want to learn that beforehand, go to the above-mentioned projects' github pages and start reading. Marco!

Wednesday, February 22, 2012

Using jQueryMobile and Backbone.js for handling forms

Introduction

In this post, I continue the development of my basic "exercise app" that I started (and enhanced) in these posts:

Let's add the ability to create and edit exercise records.

Adding a new activity

Just like in the previous post, the first thing we need is a jQueryMobile page to hold the form content. Add the following to index.html:

    
Save

New Activity

In the code above, we see the typical jQueryMobile page. The main things of interest here are with respect to the anchor tag in the header div:

  • Specify data-rel="back" to navigate to the previous page once the save is complete. This way whether we enter the form page from "Add" or "Edit", navigation will be handled.
  • The class="ui-btn-right" moves the button to the right side of the header bar.
  • The data-theme="b" causes the save button to use the blue theme.
The next step is to define the template that the view will use to render the content for this page. Lets start with a simple template with an input for each attribute of an activity. To vary the UI slightly, we can use a drop down for the activity type. The basic template will look like this:

    

Notice that we are using the HTML 5 input types for some of the fields. Browser support for these will vary, but worst case they will deprecate to a text input type. For example, on iOS, the date will present a native date picker, whereas on Android (or Chrome, etc.) the field will behave as a standard text input.

Now we need to navigate to the form page. This requires modifying the "Add" button on the list page.

    

Activities

Add

In order to transition to the form page, the href attribute on the anchor tag (i.e. button) needs to be changed to the id of the form page, as shown in line 4 above. The final step in presenting the form page to support adding exercise activities is modifying the add button click handler.

    $('#add-button').live('click', function(){
        var activity = new exercise.Activity(),
            activityForm = $('#activity-form-form'),
            activityFormView;

        activityFormView = new exercise.ActivityFormView({model: activity, viewContainer: activityForm});
        activityFormView.render();
    });

Here we create an empty model, grab the form node, create a new exercise.ActivityFormView with these objects, and render the form. Testing at this point reveals a problem. The screen shot below doesn't look right ;)

Investigating the browsers console reveals an error: Uncaught ReferenceError: distance is not defined. This is due to the underscore template trying to access an undefined attribute of the model. The issue is described here with some work arounds. I found the easiest workaround is to provide defaults for the model, as shown below.

     exercise.Activity = Backbone.Model.extend({
        defaults: {
            date: '',
            type: '',
            distance: '',
            comments: '',
            minutes: ''
        }
     });

Now the form renders properly. With the help of some CSS, we can tighten things up a little and end up with the version on the right (the CSS is part of the source code, see the links at the end of this post).

Editing an existing activity

With the template and the view already implemented, adding edit functionality is pretty straightforward. The first step is to update the href attribute of the edit button on the activity-details page.

    
Edit

Activity Details

As we did with the add button, this should reference the activity-form page. Now we need to add the click event handler for the edit button.

    $('#edit-activity-button').live('click', function() {
        var activityId = $('#activity-details').jqmData('activityId'),
            activityModel = exercise.activities.get(activityId),
            activityForm = $('#activity-form-form'),
            activityFormView;
        
        activityFormView = new exercise.ActivityFormView({model: activityModel, viewContainer: activityForm});
        activityFormView.render();
    });

If you recall, the activityId is passed to the details page view the list item click event handler. We reuse that fact here to retrieve the activity from the collection.

Time to test. Selecting an activity renders the detail page. Clicking the edit button renders the form, pre-filled with the activity details. Everything looks great.

But wait.....that screenshot was from the browser on which I am testing. We should always test on devices as well. Earlier I mentioned that we are using some of the HTML 5 input types (i.e. date). The nice thing is that iOS 5 will render a nice date picker for date types. The challenge is that the date needs to be in a specific format for that to work. The image below shows what the form page looks like on an iOS device.


Fixing the Date

No date value is showing up on our iOS device. This is a known issue. So, for iOS we need the date format as yyyy-mm-dd, while for other platforms, I prefer the date to be shown as mm/dd/yyyy. I do realize that date formats should be localized, but for the purpose of this example I would like to keep it straightforward and specify mm/dd/yyyy as the display date format. There are many options that could be pursued here, but to demonstrate some more capabilities of Backbone.js, we will modify our model to help meet our date requirements.

First, the date attribute in our JSON feed is a string. Lets convert this to a date when the data is retrieved from the server, then when we need the date, we can just manipulate it as needed. This can be accomplished several ways.

  • Implement a parse method on the collection that converts the String to a Date as the data is being fetched from the server.
  • Implement a method on the model that converts the date String to a Date and sets it on the model. This would then require the calling code to know to call this method depending upon the circumstance.
  • Override the set method on the model, look for the date attribute, then convert it to a date as needed.
The last option is the most seamless approach. Add the following method to the Activity model.

        set: function(attributes, options) {
            var aDate;
            if (attributes.date){
                //TODO future version - make sure date is valid format during input
                aDate = new Date(attributes.date);
                if ( Object.prototype.toString.call(aDate) === "[object Date]" && !isNaN(aDate.getTime()) ){
                    attributes.date = aDate;
                }
            }
            Backbone.Model.prototype.set.call(this, attributes, options);
        }

Also, update the defaults so that the date attribute is now a Date instead of a String.

        defaults: {
            date: new Date(),
            type: '',
            distance: '',
            comments: '',
            minutes: ''
        },

While this clearly isn't the most robust date handling, it is fine for now. In a future version, this should be improved.

Next, add attributes to our model that will format the date in the ways we need it (i.e. mm/dd/yyyy and yyyy-mm-dd).

        dateInputType: function(){
            return exercise.formatDate(this.get('date'), "yyyy-mm-dd"); //https://github.com/jquery/jquery-mobile/issues/2755
        },
        
        displayDate: function(){
            return exercise.formatDate(this.get('date'), "mm/dd/yyyy");
        }

The formatDate function is a simple date formatter to meet our specific needs and can be found in the source code that accompanied this post (see link at the bottom of the post).

Now, how do we use these new methods in our view. The first thing to realize is that we pass the template JSON. The default implementation of the toJSON method of a Backbone.js model will not include these functions. Therefore, we need to override the toJSON method.

        toJSON: function(){
            var json = Backbone.Model.prototype.toJSON.call(this);
            return _.extend(json, {dateInputType : this.dateInputType(), displayDate: this.displayDate()});
        }

Here, we are using the Underscore.js extend to add our attributes to the standard Backbone JSON. Now, we need to modify our view templates to use the appropriate JSON attributes.

    
    
    
    
    

Notice that lines 16-21 include some conditional logic. This is a very basic device detection check to determine which date format to use. There are plug-ins,etc. that provide more robust alternatives, but to keep things clear, this will serve our needs. The screen shots below show the desktop browser and the iOS versions of the form with the appropriate date handling.

Saving

The final step is to implement the save functionality.

    $('#save-activity-button').live('click', function(){
        var activityId = $('#activity-details').jqmData('activityId'),
            activity,
            dateComponents,
            formJSON = $('#activity-form-form').formParams();
        
        //if we are on iOS and we have a date...convert it from yyyy-mm-dd back to mm/dd/yyyy
        //TODO future version - for non-iOS, we would need to validate the date is in the expected format (mm/dd/yyyy)
        if (formJSON.date && ((navigator.userAgent.indexOf('iPhone') >= 0 || navigator.userAgent.indexOf('iPad') >= 0)) ){
            dateComponents = formJSON.date.split("-");
            formJSON.date = dateComponents[1] + "/" + dateComponents[2] + "/" + dateComponents[0];
        }
        
        if (activityId){
            //editing
            activity = exercise.activities.get(activityId);
            activity.set(formJSON); //not calling save since we have no REST backend...save in memory
        }else{
            //new (since we have no REST backend, create a new model and add to collection to prevent Backbone making REST calls)
            activity = new exercise.Activity(formJSON);
            activity.set({'id': new Date().getTime()});  //create some identifier
            exercise.activities.add(activity);
        }
    });

I used the JavascriptMVC formParams jQuery plugin (found here) to convert my HTML form into a JSON object. Then, the date is converted into the appropriate format. One thing to note here is that since we have no real back end server for Backbone to interface with, we don't call save on the model or create on the collection. These methods would cause the appropriate REST calls to the server.

Since the click event on the list view passes the activityId to the details page, we can use this to determine if we are adding or editing. One thing to consider here is that the user may click an existing activity, then go back to the list, then click add. In this case, the activityId from the previously selected activity is still attached to the activity-details view. This will cause our save implementation to think we are editing. To prevent this, we should remove the activityId from the activity-details page when adding a new activity. This can be accomplished by adding the highlighted line below to the add handler.

    $('#add-button').live('click', function(){
        var activity = new exercise.Activity(),
            activityForm = $('#activity-form-form'),
            activityFormView;
    
        //clear any existing id attribute from the form page
        $('#activity-details').jqmRemoveData('activityId');
        activityFormView = new exercise.ActivityFormView({model: activity, viewContainer: activityForm});
        activityFormView.render();
    });

The final step is to make sure our views are updated accordingly when we add or modify activities. Since the details view retrieves the activity before the page loads, no change is required here. But our list view only renders during the initial page load. This is where we can take advantage of Backbone event binding. A few small additions to the ActivityListView and things will be handled.

        initialize: function() {
            this.collection.bind('add', this.render, this);
            this.collection.bind('change', this.changeItem, this);
            this.collection.bind('reset', this.render, this);
            this.template = _.template($('#activity-list-item-template').html());
        },

        ...

        changeItem: function(item){
            this.collection.sort();
        }

The change event will bubble up from the model and fires as a result of the set being called. In the changeItem method, we sort the collection to handle any changes in the date attribute. The sort method call will cause the reset event to fire, which then results in the render method invocation, causing the list to be re-rendered. This keeps everything in the correct order. The add event will be fired when we add a new activity to the collection. Since we implemented the comparator method on the collection, models added to the collection will be added in the appropriate order.

We can now add and edit activities. Start exercising :)

The source code for this post can be found here

Wednesday, February 15, 2012

Sencha Touch 2 - NavigationView, Templates and Forms

This post will build on the example application from the Introduction to Sencha Touch post. We will look at sorting, templates, navigation and forms.

Sorting

In the existing code new items appear at the bottom of the list. I’d prefer to see the newest items first. After a Sorter is added to the Store, Sencha displays records in the proper order.
var store = Ext.create('Ext.data.Store', {
    storeId: "activityStore",
    model: "Activity",
    proxy: {
        type: 'ajax',
        url: 'exercise.json'
    },
    sorters: [
        {
            property: 'date',
            direction: 'DESC'
        }
    ],
    autoLoad: true
});

Detail View

The user should able to drill into an Activity on the list to see the details.

Template

We will create an XTemplate that will be populated with the data from the Model. Templates can be created in Javascript or externalized. I prefer to put more complex templates in HTML rather than inline Javascript. Sencha recommends external templates are defined in a hidden textarea.
<textarea id="detail-template" style="display:none">
  <div>
    Date: {date:date("m/d/Y")} <br/>
    Type: {type} <br/>
    Distance: {distance} <br/>
    Time: {minutes} minutes <br/> 
    Notes: {comments} <br/>
  </div>    
</textarea>
The template is created once in code.
var template = Ext.XTemplate.from(Ext.get('detail-template'));

List item disclosure

Sencha displays a disclosure icon for each row when a function is assigned to the onItemDisclosure property of the list. Clicking on this icon allows the user to drill into the details for a row.
The onItemDisclosure function
  • receives the selected record as an argument
  • populates the template with the model’s data
  • creates a new panel
  • pushes the panel onto the navigation view
   {
       xtype: 'list',
       title: 'Activities',
       itemTpl: '{date:date("m/d/Y")} - {type}',
       store: store,
       onItemDisclosure: function (record, btn, index) {
           view.push({
               xtype: 'panel',
               title: 'Activity',
               html: template.apply(record.data),
               styleHtmlContent: true
           });
       }
   }

Pushing the panel onto the NavigationView handles a lot of stuff. The view becomes visible, the navigation bar title is set, a back button is displayed, navigation is handled automatically. This is a nice new feature in Sencha Touch 2.0.

Disclosure icon Record detail

Showing and hiding buttons

When the user is viewing the details, the Add button should disappear. We can manually hide the button in the onItemDisclosure before pushing the view.
onItemDisclosure: function (record, btn, index) {
                      view.down('#addButton').hide();
                      view.push({
                      // ...
The Add button needs to be shown again when the user navigates from the detail back to the main screen. Since the NavigationView handles the navigation automatically, we listen for the pop event and make the Add button is visible.
var onNavigationPop = function(v, item) {
   v.down('#addButton').show();
};

var view = Ext.create("Ext.NavigationView", {
   fullscreen: true,
   items: [
      // ...
   ],
   listeners: {
       pop: onNavigationPop
   }
});
Similarly, we can add onNavigationPush to hide the Add button whenever we push a new view on the stack. This is better than hiding the button in onItemDisclosure.
var onNavigationPush = function(v, item) {
    v.down('#addButton').hide();
};

var view = Ext.create("Ext.NavigationView", {
   fullscreen: true,
   items: [
      // ...
   ],
   listeners: {
       pop: onNavigationPop,
       push: onNavigationPush
   }
});

Record detail with button Record detail without button

Finally, instead of word Add on the button, I think it looks better with an icon.
view.getNavigationBar().add([
  {
      xtype: 'button',
      id: 'addButton',
      align: 'right',
      ui: 'action',
      iconCls: 'compose',
      iconMask: true, 
      handler: addNewRow
  }
]);

Add button text Add button icon

Adding new records with a form

The current implementation puts a fake row into the store when the Add button is pressed. We want to display a form to collect the user input.
We are going to change the implementation of addNewRow to create a FormPanel and push it onto the view. The NavigationView destroys components as they are popped, so we recreate the form every time. Alternately we could set autoDestroy to false on the NavigationView.
var addNewRow = function() {
    view.push(Ext.create('Ext.form.Panel', formBase));
};
The formBase object contains the form fields.
var formBase = {
    title: "Activity",
    itemId: "form",
    items: [
        {
            xtype: 'datepickerfield',
            name: 'date',
            label: 'Date',
            value: new Date()
        },
        {
            xtype: 'selectfield',
            name: 'type',
            label: 'Type',
            options: [
                { text: "" },
                { text: "Run", value: "Run" },
                { text: "Bike", value: "Bike" },
                { text: "Swim", value: "Swim" },
                { text: "Walk", value: "Walk" }
            ]
        },
        {
            xtype: 'textfield',
            name: 'distance',
            label: 'Distance'
        },
        {
            xtype: 'numberfield',
            name: 'minutes',
            label: 'Minutes'
        },
        {
            xtype: 'textfield',
            name: 'comments',
            label: 'Notes'
        }
    ]
};

Saving data

The navigation bar needs a save button. Initially this button will be hidden.
{
    xtype: 'button',
    id: 'saveButton',
    text: 'Save',
    align: 'right',
    ui: 'action',
    handler: save,
    hidden: true
}
The addNewRow function makes the save button visible.
var addNewRow = function() {
    view.push(Ext.create('Ext.form.Panel', formBase));
    view.down('#saveButton').show();
};
The save button is hidden in onNavigationPop.
var onNavigationPop = function(v, item) {
    v.down('#addButton').show();
    v.down('#saveButton').hide();
};
The save function
  • gets the form using the item id
  • creates an new Activity model from the form data
  • adds the new model to the store
  • navigates back to the list view
var save = function() {
   var form = view.down('#form');
   var record = Ext.create('Activity', form.getValues());
   store.add(record);
   // TODO validation and error handling
   view.pop();
};

Note that Sencha automatically displays the new data in the list without any effort on our part.

Form New row

Additional enhancements to improve this example could include things like validating form data, editing existing rows, sending data back to the server, converting to MVC.

The source code is available on github.

Monday, January 30, 2012

From a List to a Details View using jQueryMobile and Backbone.js

In my previous post I built a basic application to demonstrate the use of Backbone.js with jQueryMobile (JQM). The introduction can be found here, with a brief subsequent post on sorting collections here. In this post, I would like to add the capability to view the details of the items presented in the list view.

The first step is to create a new JQM page to display the details view. JQM makes it pretty easy to add pages to your application. I added the following code to the index.html file:

This will create the structure for the page, and Backbone.js will be used to fill in the content div based on the record tapped (or clicked) within the list view. The next step is to define the template for the details view. This is the pattern that I follow when developing using jQueryMobile and Backbone.js. The template can be inserted below the list item template in index.html.

I decided to embed the details in a read-only list view, this way jQueryMobile will provide some reasonable styling. Since the point here is to demonstrate Backbone and jQueryMobile playing together, I didn't want to have to spend much time on style :)

Next, we need to define the Backbone view that will use the template to render the appropriate content. All this View needs to do is apply the model to the template and append it to the HTML container defined when the View is instantiated.

In order to retrieve the correct model to bind to the details view, we need to know what row in the list view was clicked (or tapped). To do this, we can bind to the click event of the item in the list view. This can be accomplished by modifying the ActivityListView render method. Here is the current version of the list view:

The key area to focus on here is lines 18-20, where the activity item HTML is rendered and appended to the list view. This is where the modification needs to occur. Each activity item HTML element needs to be bound to a click event. In this click event, the activity id will need to somehow be passed to the details view so the appropriate look up can occur. There are several ways to do this. Approaches I have used in the past include the use of jQuery.jqmData(...) or session local storage (assuming HTML5). In this example, we will use the jqmData method. The trick is to capture the id during the rendering of the list so that it can be used during the execution of the click event. Below are the required modifications to lines 18-20 of the previous code snippet.

The first thing is to capture the rendered activity item HTML in a variable and cast it to a jQuery object, as can be seen in lines 2-3. Line 4 is where the activity id data is attached to our activity item HTML element. Then, the bind event (lines 5-8) retrieves the attached data and sets it on the activity details HTML element, which is our activity details page HTML. Per the jQuery documentation, this within a bind method refers to the DOM element to which the event handler is bound. We can use that to get at the activity id data and attach it to the details view. This gives us the ability to pass the appropriate id at runtime to the details page.

Now we need to wire all this together. The typical pattern I follow is to use the jQueryMobile pagebeforeshow event to set up everything needed to render a complete page. This acts as my controller.

This code retrieves the id data attached to the activity details element, looks up the model using the Backbone API (line 5), instantiates the view with the model and the view container, and calls the render method to render the final HTML. The end result looks like this:

The source code for this post can be found here. Note that this is a branch of my repository for this sample app. Each blog post associated with this code base resides on a separate branch.

Related Posts:

Monday, January 23, 2012

Introduction to Sencha Touch

Steve Smith recently looked at jQuery Mobile and Backbone using a simple application that allowed a user to track their daily exercise. I'm going to duplicate his example using Sencha Touch.

Sencha Touch is a framework for building mobile applications using HTML5, CSS3, and Javascript.  This example uses the Developer Preview of Sencha Touch 2.0.

Here's what our project looks like.

A Sencha Touch application is loaded from an HTML page. The HTML loads CSS and Javascript. Sencha Touch applications typically build the UI using Javascript so the index.html is very simple.

The touch/ directory contains the Sencha Javascript and CSS from the SDK.  Since this is an example, all if the application code is in one file, app.js. Larger applications will break the code up into more files and directories.

Sencha Application

Sencha Touch has a global namespace, Ext, that holds the framework and application code. The Ext.application helper function takes a configuration object where we define our application.

Ext.application({
    launch: function() {
        // define our app here
    }
});

Model

We extend Ext.data.Model to define a Model object describing our data. The data is supplied by the server in a JSON file, exercise.json. The fields in the model, match the properties in the JSON file.

Ext.define("Activity", {
    extend: "Ext.data.Model",
    fields: [
        {name: 'id', type: 'int'},
        {name: 'date', type: 'date'},    
        {name: 'type', type: 'string'},    
        {name: 'distance', type: 'string'},    
        {name: 'minutes', type: 'int'},  
        {name: 'comments', type: 'string'}
    ]
});
/* exercise.json */
[
    {
        "id":3,
        "date": "12/10/2011",
        "type": "Walk",
        "distance": "2.5 miles",
        "comments": "Shouldn't have taken the dog",
        "minutes": 45
    },
    ...
]  

Store

A Store is used to load and manage data. The Activity model we created is associated with the store. We define a proxy to load the JSON data from a URL. Finally, we tell the store to automatically load the data when the store is created.

var store = Ext.create('Ext.data.Store', {
    storeId: "activityStore",
    model: "Activity",
    proxy: {
        type: 'ajax',
        url: 'exercise.json'
    },
    autoLoad: true
});

Once the store is created, we can use the Javascript console to interact with the data.

User Interface

Now we need to display the data. A NavigationView shows a navigation bar and holds the List component. The list is defined in the code using the object literal syntax. The data store we created is assigned to the list so it can display the records. The itemTmp property defines how to display each item of data. This can be a template or a string.

var view = Ext.create("Ext.NavigationView", {
    fullscreen: true,
    items: [
        {
            xtype: 'list',
            title: 'Activities',
            itemTpl: '{date} - {type}',
            store: store
        }
    ]
});
Unformatted Date

This works but the date doesn't display very well. A format can be added to the template definition. {date} in the itemTpl becomes {date:date("m/d/Y")}.

var view = Ext.create("Ext.NavigationView", {
    fullscreen: true,
    items: [
        {
            xtype: 'list',
            title: 'Activities',
            itemTpl: '{date:date("m/d/Y")} - {type}',
            store: store
        }
    ]
});
Formatted Date

Adding New Data

Let's add a button to the header to add a new row of data.

view.getNavigationBar().add({
    xtype: 'button',
    text: 'Add',
    align: 'right',
    handler: addNewRow
});

The handler property of the button defines the function that is called whenever the button is pressed. Eventually we need a form so the user can add new data. For now, let's define a function addNewRow that will create a new row and add it to the store.

var addNewRow = function() {
    // future versions should display a form for adding a record
    var fakeRecord = Ext.create('Activity', {
        date: new Date(), 
        type: 'Walk', 
        distance: '2 miles', 
        minutes: 28, 
        comments: 'Auto generated record.'
    });

    store.add(fakeRecord);
};

Now when the button is pressed a new row appears in the UI.  The store notifies the list, so rows appear as records are added to the store.

Add Button

New Row

That should be enough to get you started. In future posts we'll look at features like sorting, detail views, navigation, and forms. The source code is available on github.

Tuesday, February 1, 2011

Executing JavaScript from Objective-C in an iOS App

New blog post from Steve Smith, one of the Chariot architects working in our mobile practice.  Steve is currently working on updating the mobile app for our Emerging Technologies conference and will be posting articles from time to time as he finds challenges or discoveries.

Here is an excerpt:

The other day, I found the need to execute some JavaScript from a native iOS application.  After doing a little research, I discovered that the UIWebView has a stringByEvaluatingJavaScriptFromString method.  So I decided to create a quick little proof-of-concept to see how to invoke some JavaScript using this. I am not going to walk through all the details of creating a project, etc. and will cut right to the important aspects of making the JavaScript call from the objective-c code.
We are going to need a JavaScript function to call and a UIWebView to evaluate the JavaScript. It would be nice if the JavaScript function took a parameter as well, so we could also prove out the passing of values.  Here is the JavaScript function that I will use:
1var area = function(diameter) {
2     var radius = diameter/2,
3     area = Math.PI * radius * radius;
4     return Math.round(area*100)/100;
5};


Read more

Monday, January 10, 2011

An Introduction to Mobile Device Detection

One of our architects, Steve Smith, recently posted this on his blog:

These days, there are many ways to browse the internet.  There are desktop browsers, mobile phone browsers, tablets, tablet/phones (e.g. Dell Streak), etc. all with different screen sizes, resolution, and capabilities.  How do you render an appropriate view optimized for the device accessing your site?  The answer is device detection.
The two main approaches for device detection are server-side detection and client side detection.  Server side detection involves determining the device at the time of the request and then presenting the appropriate view.  Client side detection involves manipulating the view after the content has been sent to the browser.

Read the full post..