Thursday, May 29, 2014

Knockout checkbox binding to string

As you know knockout has “checked” binding that allows you to bind your Boolean observable to a checkbox. But there may be situations where you will have your checked value as string, for example “yes”.

One approach for this is to define a computed observable and bind it to the checkbox. But the problem is for every checkbox you need to define a computed observable, which causes code bloating. Instead of this let’s create custom binding which accepts a string (yes/no) and binds the checkbox. Here is our code for this custom binding

    ko.bindingHandlers.customcheck = {
        init: function (element, valueAccessor, allBindingsAccessor, data) {
            var value = valueAccessor();
            if (value().toLowerCase() === "yes")
                value(true);
            else
                value(false);

            ko.applyBindingsToNode(element, {
                checked: value
            });
        }
    };

As you see in the above code, I am actually changing the value of my observable. If you prefer you can define your own computed observable inside this custom binding and use it, so that you don’t have to change your observable.

    ko.bindingHandlers.customcheck = {
        init: function (element, valueAccessor, allBindingsAccessor, data) {
            var value= valueAccessor();
            var checkbool = ko.computed({
                read: function () { return (value().toLowerCase() === "yes"); },
                write: function (boolvalue) { value(boolvalue ? "Yes" : "No"); }
            });

            ko.applyBindingsToNode(element, {
                checked: checkbool
            });
        }
    };

Either of the above approaches will let you bind your checkbox to a string value.

Wednesday, May 28, 2014

Knockout EnterKey

There may be scenarios where you want to do something when user clicks enter key. Be it on a textbox or any control in the form. The html form has an ability to auto submit the form when user presses enter key. Also knockout has submit binding which allows you to handle enter key on a form. The html form submit and knockout’s submit binding may not be suitable in many scenarios. For example I am working on a SPA login page where I want to authenticate user after he presses enter key. As this is a SPA application there is no significance of form here. Even if I use form, the knockout submit event is not firing as I am using durandaljs.

In this blog I will show you how to write a custom binding which listens to the enter key in a form and raises the corresponding event. This custom binding can also be applied to a text box.

Creating an “enterKey” binding is very easy, all you need to do is listen to the enter key code and call the method that is associated with the binding. We will do this in the init callback. Here is the code

    ko.bindingHandlers.enterkey = {
        init: function (element, valueAccessor, allBindingsAccessor, data) {

            ko.utils.registerEventHandler(element, "keyup", function (e) {
                if (e.keyCode === 13) {
                    valueAccessor().call(data);
                }

            });
        }
    };

As you see this a simple code where I am registering the key up event on the element, when the user presses enter key (keycode = 13), I am calling the associated method. Here is how I use the enterkey binding on a form

<form method="post" data-bind="enterkey: validate">

Please note that in some scenarios you may want your textboxes to update on a keyup as the enterkey does not trigger the update of the corresponding textbox.


<input type="text" placeholder="Username" data-bind="value: model.UserName, valueUpdate: 'keyup'"/>

Thursday, May 22, 2014

C# 6.0 Do I need it?

If you haven't gone through the list of changes in C# 6.0, please take a look at this MSDN post

In my opinion there is no real need for me to jump to C# 6.0. Unlike other C# releases, with this release Microsoft hasn't made any significant changes. I believe there is a reason for this. Microsoft and C# team really focused on the Roslyn compiler initiative and didn't have much time for this version. I feel they should have versioned this as C# 5.1 and not C# 6.0.

Anyway of the new changes the one thing I liked very much is the Exception-Handling improvements. This functionality currently does not exist and would help to catch a precise exception. Apart from this rest of features are syntactic sugar and in some cases makes the code sloppy.

Here is my take on these other new features:

Indexed Members and Element Initializers - This feature seems interesting and will help reducing the code. But somehow I don't like the $ keyword for wrapping my strings to objects. The good news is now we got $ in C# code :)

Auto-Properties with Initializers - I liked this syntactic sugar and will use from day one. This eliminates the need for a constructor to initialize my properties

Primary Constructors - This syntactic sugar is very confusing. I see how this reduces my code, but also adds confusion. I will be little bit hesitant to use this feature at the onset.

Static Using Statements - Another syntactic sugar, I am not excited about. I believe this leads to sloppy coding. On average a typically developer productivity is 25 to 50 lines code per day. I don't mind few additional key stokes if I can make my code more readable.

Declaration Expressions - Again I feel that this feature also promotes sloppiness and confuses developers. I am currently happy without this feature.

Binary Literals - Well this is an interesting feature and may help in code readability. I didn't see much use of this in my existing projects other than the binary flags mentioned in the MSDN blog.

As you see most of the syntactic sugars above does not add a great value and some may even confuse you. If you read the comments in the MSDN blog, most of the developers are not happy with these syntactic sugars. I feel that a language should be simple without too many bells and whistles.


Hence I am not excited with the new features of C# 6.0. But I am super excited with the Roslyn and open sourcing .NET.

Thursday, May 8, 2014

JavaScript Enums

We all know the advantages of enums. These help code readability, reduce hard coding and much more. Wouldn’t be great we have the same support in our javascript code. Unfortunately javascript does not provide this support out of box. There are several ways you can accomplish this functionality. In this blog I will show one such approach.
Javascript provides a loose syntax where you can specify your properties without first defining them. I will take advantage of this and define my enums as below.
    this.enum = new Object();

    this.enum.notesType = {
        New: 1,
        Correct: 2,
        Saved: 3,
        Default: 4
    };

    this.enum.fieldType = {
        Notes: 0,
        Patient: 1,
        Default: 2
    };

As you see, I first initialized a variable called enum. I used the name “enum” to say that all the properties of this object are of enum values. Later I define an enum similar to what we do in a traditional server side code such as C#. Now this enum can be used in our code as below:
    if (notestype === enum.notesType.Default) {
        //do something
    }

With this little trick we can bring the enums we know to javascript. Wait a minute we can even make it better in javascript. Check this enum definition
    this.enum.module = {
        patient: 'patient',
        user: 'user'
    };

That’s correct we can define strings in javascript enums, which is not possible in C#.