Archive for the ‘javascript’ Tag

Syncronizing time/watch between javascript client and ASP.NET MVC 4 server

I just wished working with Date() in Javascript was easier.
Recently here at 4N1, we had to make some date-time calculations on the client-side of a web application. The app arquitecture is:

Client side

  • Html 5: Just added the 5 to look cool. 😀
  • Javascript: You know what that is.
  • Knockout JS: An amazing Javascript MVVM framework.
  • TaffyDB: An awesome Javascript database.

Server side

Since the client and the server time can be different, we need a way to know exactly how much it is to adjust our calculation. Talking with an old colleague, Rui Milagaia, the following solution came up:

Time sync Logic

A device is anything that has a time. This logic can be applied in any scenario(computer A to computer B, client to server, server to server, device A to device B, etc).

NOTE: This solution will not guarantee milliseconds precision but if your doing calculations that go only down to the second, it should be ok.

Back to our app, since is javascript, I’ve used jquery to perform an ajax request to an MVC Action. I just needed to guarantee that the request was synchronous, otherwise the asynchronous behavior adds noise to the calculated value. I’ve created a github repository with the source code here. You can use it with another server side technologies (JSP, Rails, Grails, etc). Here is the important steps:

Client side

  1. Add a reference to the 4n1.timesync.js file:
    <!-- jQuery 1.5 or later is a foranyone.timeSync dependency -->
    <script src="jquery-1.6.4.js" type="text/javascript"></script>
    
    <!-- Reference to the 4n1.timeSync script file-->
    <script src="4n1.timeSync.js" type="text/javascript"></script>
    
    <!-- To make it easier to parse date strings with the ISO 8601 format, we use the library from https://github.com/csnover/js-iso8601 -->
    <script src="iso8601.js" type="text/javascript"></script>
    
  2. Set the expected properties, in my case only the url to the MVC Action, and call the foranyone.timeSync.getTimeDifference function to retrieve the time difference in milliseconds.

    foranyone.timeSync.url = "www.somedomain.com/ServerTime/GetServerTime";
    
    // This variable now has the difference from the client and the server in milliseconds. It can be positive or negative.
    var timeDifference = foranyone.timeSync.getTimeDifference();
    
  3. Server side

    1. Just implement an action that returns the server time:
      public class ServerTimeController
      {
          public ActionResult GetServerTime()
          {
              // Using a Iso format string without all the milliseconds because IE cannot process it :p. 
              return Json(DateTime.Now.ToString("yyyy'-'MM'-'ddTHH':'mm':'ss.fff%K"), JsonRequestBehavior.AllowGet);
          }
      }
      

    And thats it. Happy syncronization! 😀

Kockout performance tip #1

After reading two posts(#1 and #2) from one of the Knockout project members, Ryan Niemeyer, I did some performance testing on my application and found an improvement:

The Problem: Rendering and processing elements that are not visible

<table data-bind="foreach: Items">
	<tr>
		<td data-bind="text: Name"></td>
		<td>
			<input type="button" data-bind="click: edit" value="Edit"/>
		</td>
	</tr>
	<tr data-bind="visible: IsEditing()">
		<td colspan="4" style="background: white;">
			<table data-bind="foreach: SubItems">
				<tr>
					<td data-bind="text: Name"></td>
				</tr>
			</table>
		</td>
	</tr>
</table>

This code creates a table with two rows for each Master Item (in the Items list):

  • A row with the Item name and an Edit button
  • Another row with an inner table with the list of the child items (in the SubItems list).

The thing is, the second row only appears when the user clicks on the Edit button (callind the Item.edit method, witch in turn changes the IsEditing to true). With the code above, Knockout was processing all bindings (even the ones from the SubItems). Depending on the amount of SubItems or bindings, the ko.applyBindings method can taking quite some time.

The Solution: Using an If binding to control witch elements are rendered and processed

<table data-bind="foreach: Items">
	<tr>
		<td data-bind="text: Name"></td>
		<td>
			<input type="button" data-bind="click: edit" value="Edit"/>
		</td>
	</tr>
	<tr data-bind="if: IsEditing()">
		<td colspan="4" style="background: white;">
			<table data-bind="foreach: SubItems">
				<tr>
					<td data-bind="text: Name"></td>
				</tr>
			</table>
		</td>
	</tr>
</table>

Changing the visible binding to the if binding, made Knockout only process and render the details row (with all the SubItems) when the Master Item was being edited. In my page (a lot more complex than the example above and with a lot of data), it made the ko.applyBindings execution 2 seconds faster.