Welcome...



...All those moments will be lost in time, like tears in rain....

- soliloquy from Blade Runner


Bits and bytes do get lost, awash in the rain of data flow that is Internet. They slip away from us, never to found again... some of them will be captured here, many more will not... like tears in rain...



Thursday, July 26, 2012

Knockout.js

 I've heard about knockout.js when I was reading one of MVC posts from Steven Sanderson. His books are great, so I took note of that library, but didn't have time to try.

 So I did went to a meetup yesterday, and it was very useful. MVVM pattern is not something I've encountered before - in the nutshell, it's basically separation of UI logic from business logic. It allows for data binding between model and views - in "viewmodel" part.

 To do that, knockout uses data attribute from HTML5 - data-bind construct allows objects to be bound to html elements.

Simple example:

View:

<p>First name: <strong data-bind="text: firstName"></strong></p>

<p>First name: <input data-bind="value: firstName" /></p>

<button data-bind="click: capitalizeLastName">Go caps</button>

ViewModel:

function AppViewModel() {
    this.firstName = ko.observable("A");

    this.capitalizeFirstName = function() {
        var currentVal = this.firstName();        // Read the current value
        this.firstName(currentVal.toUpperCase()); // Write back a modified value
    };    
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());


 Interactive tutorial is available on their site:


Knockout.js tutorial

It's very object oriented javascript (who said Javascript is not object oriented language ? :)) and it makes sense when you read the code - it's very good library. I know how to do those things manually in javascript because I have been working with javascript for 10+ years, but this little library makes development easier and end code more readable. 

 Best part is that knockout will be included with Visual Studio 2012, since it works very nicely with MVC 4.0 and jQuery.

No comments:

Post a Comment