KnockoutJS – what I’ve learned so far
I have been using KnockoutJS at work for the last few weeks and thought it might be an idea to blog about my findings whilst using KnockoutJS within an MVC 4 project, so here goes: –
-
With KnockoutJS you can get a really slick user experience if you show discipline in structuring your code, you can separate out your concerns using unobtrusive JavaScript – i.e. don’t put your JavaScript in the HTML, yes add data-bind attributes but that should be all you need, your JavaScript can be referenced from a file within a JS folder or similar keeping your HTML clean and free from being polluted by lots of inline JavaScript.
-
If you’re wondering how you go about going from your MVC model and working with this in KnockoutJS then look no further than KnockoutJS mapping. This plugin will take your existing Model from c# and convert it into what you will use within KnockoutJS, for example if in your model you have a string[] defined like so:-
[sourcecode language=”csharp”] public string[] EmailAddresses { get; set; }
[/sourcecode] then the mapping plugin converts this to an observableArray, and if you have a simple string property such as: –
[sourcecode language=”csharp”] public string Email { get; set; }
[/sourcecode] then the plugin will map this to a knockout observable for you. -
When using ObservableArrays note that the number of items in the array is tracked – not the actual values within the array – this is important if, if the front end requires updated to the values within the array then you need to make the items within the ObservableArray observable also.
-
Take a look at the ko.utils code mentioned here for some hidden gems when working with KnockoutJS.
-
Dont store a lot of information in observables if you don’t have to, it’s not a good idea to store 10,000 records in an observable array and then bind that to a grid (Only store what you need in observables)
-
It can be a good idea to display on your page the contents of your viewmodel whilst you’re debugging so you can see what the observable and observable arrays you’re using contain
[sourcecode language=”csharp”] <div id="debug" style="clear: both">
<hr />
<h2>Debug</h2>
<div data-bind="text: ko.toJSON($data)" />
</div>
[/sourcecode]
More soon as I use it more and more, hope that helps.