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