Wednesday, April 23, 2014

Defining JavaScript class in Knockout

We all know how to write a class in traditional languages such as C#, Java etc. With more trend towards Single Page Applications we are all moving towards writing JavaScript classes. In this blog I will present my preferential way of writing a JavaScript class while using Knockout. The approach is generic enough you can use this with another framework

Here is my typical structure:

define([], function () {
    var title = ko.observable();
    var vm = {
        activate: activate,
        title: title
    };

    return vm;

    function activate() {
        return true;
    }
});

There are 4 sections in this structure. Here are the details of each section

1.       At the top I am using AMD module loaders such as RequireJS to load all the dependencies. This is like include files.
define([], function () {
   // Your class code
});

2.       Once all the dependencies are loaded. I define all my private variables.
var title = ko.observable();

3.       This is the most important piece. This section contains the public properties our javascript class exposes. This like an interface in C#. Using this we can restrict what the consumer can access our object.
    var vm = {
        activate: activate,
        title: title
    };

    return vm;

As you see I am allowing consumers to access activate method and the property title.

4.       In this last section we can define all our functions (both public and private)
    function activate() {
        return true;
    }

As you see with this structure you can get the feel of a traditional class in JavaScript.

Friday, April 18, 2014

Session and Profile in Knockout Durandal SPA

Session and Profile is not a typical tenants of a single page application. But coming from a web development background we are so much used to these words. Hence I decided to carry the same terminology to the SPA also.

As you know Session is used to persist data between pages and Profile is used to store user details.  Let’s take the same concepts to the single page application. Web applications are stateless in nature and hence we need complex patterns to persist the state. Whereas SPA is a statefull environment running in a browser. Hence persisting state is very simple. But you need to be cautious and keep an eye for memory leaks and too much memory usage.

I will declare a global object (called session) and store that object in the window object. Here is my code for this session object

define(['services/profile'], function (profile) {

    var lookups;
    var vm = {
        profile: profile,
        lookups: lookups  //any additional data you want to persis
    };

    return vm;

});

As you see I am currently persisting profile data in session object. In addition I am also persisting additional data (lookups).

My profile object stores user details and is also used to check whether user is logged in or not. Here is the complete code for of my Profile object

define([], function () {
    var userID = ko.observable();
    var firstName = ko.observable();
    var lastName = ko.observable();
    var userName = ko.observable();
    var isAuthenticated = ko.observable(true);


    var vm = {
        userID: userID,
        firstName: firstName,
        lastName: lastName,
        userName: userName,
        photoUrl: photoUrl,
        isAuthenticated: isAuthenticated,
        populate: populate,
        logout: logout
    };

    return vm;

    function populate(data) {
        this.userID(data.UserID);
        this.firstName(data.FirstName);
        this.lastName(data.LastName);
        this.userName(data.UserName);
        this.isAuthenticated(true);
    };

    function logout() {
        this.isAuthenticated(false);
    };
});

Finally we need to define this session object and set it in the window object. We will do this in the Shell. Here is the simplified version of my shell class

define(['plugins/router', 'services/session'], function (router, session) {

    function activate() {
        //routing logic goes here
      
        //global variables
        window.session = session;

    }
}

As we transition from stateless environment to statefull environment we need to shift our mindset and embrace the client paradigm and take the solutions for the problems that are already solved by client server folks.

Wednesday, April 16, 2014

DurandalJs User Authentication

As you know for most business application user authentication is needed. These applications should allow only authenticated users to access them. With the trend towards building SPA application increasing, the need for user authentication in these SPA applications also increases. We need to authenticate users similar to what we were doing in the traditional web applications.

The user authentication in SPA applications poses us a challenge. As you know SPA applications runs on browser and makes REST requests to web server. Hence we need to authenticate user both in the SPA application and also in the web server. A note of caution is that user can manipulate javascript and can bypass your security in the SPA application, hence doing authentication and authorization on the server is a must.

In this blog I will talk on how to authenticate use in the SPA (DurandalJS) application. In the subsequent blog I will cover on how to authenticate on the server and ensure only authenticated users access the server resources.

Fortunately DurandalJS provides us all the necessary plumbing code. This is done through a method called guardRoute, which enables you to check whether user has permissions to access a route or a page.

router.guardRoute = function (instance, instruction) {
    //verify user authentication and authorization
    }

From this guardRoute you can return a Boolean whether user is allowed or not, or a view that needs to be called if user is not allowed. You can even return a promise. Checkout the DurandalJS site for more information.


In my example I return a string (view) which needs to be called if user is not authorized. Here is my guardRoute  code

//setting up the guardRoute
router.guardRoute = function (instance, instruction) {
    if (session.isAutenticated() === false && instruction.config.route !== "login") {
        return 'login';
    }

You need to have this code in shell.js.

As you see in the guardRoute I am checking user is authenticated or not and redirecting user to the login page. I am storing user authentication information in an object called session which is stored in the windows object.

In my login page, once user is authenticated on the server I set the isAuthenticated to true. Similar when user logs out, I set the isAuthenticated to false. guardRoute function takes care of everything else. Isn’t that neat. As you see DurandalJS makes user authentication very easy.

P.S. It seems that DurandalJS is not going to include Knockout in their subsequent releases. We need to wait and see what’s next there.

Wednesday, April 9, 2014

Bundle Knockout Data-Bind

In one my projects I ran into a scenario where I need to specify multiple bindings for a textbox. Here is the code I used to this multiple bindings

<input type="text" data-bind="value: model.Allergies.Value,
css: {focusctrl: model.Allergies.ColourType() === 1,
correctctrl: model.Allergies.ColourType() === 2},
event: { focus: function() {$root.resetColour(model.Allergies)} }" />

The problem here is have several of these text boxes (about 50, I guess not a good design, but is what the user wants). I don’t want to repeat this binding several times (DRY). I want to bundle these bindings (like a function) so that I can avoid duplication and keep the code clean.

Luckily Knockout provides the functionality I am looking. It provides “ko.applyBindingsToNode” to dynamically do the databinding. So I defined a custom binding in which I am in turning doing the databinding I want. Here is my custom binding

ko.bindingHandlers.notesvalue = {
    init: function (element, valueAccessor, allBindingsAccessor, data) {
        var field = valueAccessor();
        field.focusctrl = ko.computed(function () { return field.ColourType() === 1 });
        field.correctctrl = ko.computed(function () { return field.ColourType() === 2 });
        ko.applyBindingsToNode(element, {
            value: field.Value,
            css: { focusctrl: field.focusctrl, correctctrl: field.correctctrl },
            event: {
                focus: function() {
                    if(field.ColourType() === 1){
                        field.ColourType(0);
                    }
                }
            }
        });
    }
};

In the above code, I am just using the initializer and doing the bundling of the value, css and event data-binding. As you see, in the above code I am also defining computed attributes. That’s neat.

With my bundling code my databinding is reduced to as below

<input type="text" data-bind="notesvalue: model.Allergies" />

This is something I can live with. J.