Knockout MVVM Javascript

Knockout allows you to bind the HTML to your javascript object. It simplifies DOM manipulation and allow the portability of the javascript object and action. It is pretty much the same concept as MVVM in silverlight. You can wire up the function with button click easily, you can have for each against your array (e.g like repeater). It is so elegant, but debugging sometimes can be challenging as well. I’ve used Knockout along with JSON that allows me to build rich and interactive website

2 powerful function: ko.observable – this allow knockout to monitor this object value, ko.observableArray this is the extension of ko.observable against the array. With observable, knockout will keep tracking the value of that property and allow the DOM that has been bind against it to refresh

You can bind initial data from your MVC model to the variable in javascript and bind it, in this sample below, I use ToJson extension function

Code Snippet
  1. namespace System.Web.Mvc
  2. {
  3.     public static class HtmlHelperExtensions
  4.     {
  5.         ///<summary>
  6.         /// Serializes an object to Javascript Object Notation.
  7.         ///</summary>
  8.         ///<param name=”item”>The item to serialize.</param>
  9.         ///<returns>
  10.         /// The item serialized as Json.
  11.         ///</returns>
  12.         public static string ToJson(this object item)
  13.         {
  14.             return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(item);
  15.         }
  16.     }
  17. }

Sample code

Code Snippet
  1. <script type=”text/javascript”>
  2.     var initialData = @(new MvcHtmlString(Model.ToJson()));
  3.     function JobResultViewModel()
  4.     {
  5.         var self = this;
  6.         self.Jobs = ko.observableArray(initialData.JobSearchResults);
  7.         self.Search = ko.observable(initialData.JobSearchModel);
  8.         self.Pageno = ko.observable(initialData.PageNo);
  9.         self.TotalPage = ko.observable(initialData.TotalPage);
  10.         self.TotalRecord = initialData.TotalRecord;
  11.         self.ShowNextButton = ko.computed(function(){
  12.                                             return self.Pageno() < (self.TotalPage() – 1);
  13.                                             });
  14.         self.LoadNextPage = function() {
  15.                                $.getJSON(@Url.Action(“ResultJson”), {  Keyword: (self.Search().Keyword == null) ? “” : self.Search().Keyword,
  16.                                                                       ProfessionId: self.Search().ProfessionId,
  17.                                                                       RoleIds: self.Search().RoleId,
  18.                                                                       SalaryTypeId: self.Search().SalaryTypeId,
  19.                                                                       SalaryFromId: self.Search().SalaryFromId,
  20.                                                                       SalaryToId: self.Search().SalaryToId,
  21.                                                                       LocationId: self.Search().LocationId,
  22.                                                                       AreaIds: (self.Search().AreaId.length == 0) ? 0 : self.Search().AreaId,
  23.                                                                       WorkTypeId: self.Search().WorkTypeId,
  24.                                                                       Pageno: self.Pageno() + 1
  25.                                                                    }, function (SearchResult) {
  26.                                                                             $.each(SearchResult, function(i, item)
  27.                                                                             {
  28.                                                                                 self.Jobs.push(item);
  29.                                                                             });
  30.                                                                             self.Pageno(self.Pageno() + 1);
  31.                                                                             //we need to refresh the repeater when we use jquery mobile ONLY
  32.                                                                             $(“#JobRepeater”).listview(“refresh”);
  33.                                                                         });
  34.                                         }
  35.     }
  36.     ko.applyBindings(new JobResultViewModel());
  37. </script>
  38. <h2>Result</h2>
  39. <h1>There are <span data-bind=”text: TotalRecord”></span> jobs</h1>
  40. <a>Save Search</a>
  41. <ul name=”JobRepeater” id=”JobRepeater” data-role=”listview” data-bind=”foreach: Jobs”>
  42.     <li><a data-bind=”attr: { href: UrlAction, title: JobName },text : JobName”></a><span data-bind=”text: Description”></span></li>
  43. </ul>
  44. <div data-bind=”visible: ShowNextButton”>
  45.     <input type=”button” id=”btn_load_next” value=”Load More” data-bind=”click: LoadNextPage”/>
  46. </div>

Source:

Knockout Tutorial

Knockout Tips

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s