Introduction
JavaScript is a very powerful scripting language and in the recent past many libraries has come over to facilitate its power by creating wrapper libraries on top of it. One of those well known is the JQuery plug and play library that brings a lot to the developers giving a complete flexibility to do complex operations, client side validations, asynchronous calls and lot more while hiding the under lying complexity of such operations from the developers. A few more addition under the hood of JavaScript libraries has gained importance recently which deserves special attention (at least I am paying to it). Out of those, I am listing only my favorite two
a) Knockout.js
b) Linq for Javascript (Linq.js)
Background
JQuery is undoubtedly one of the best JavaScript plug and play libraries. But there are other libraries which when added with JQuery may bring lot of power to the developers for writing scripting code. In this article, we will introduce ourselves with those libraries which I think needs to have some attention.
An Introduction to MVVM pattern in JavaScript using Knockout
What is Knockout?
Knockout is a JavaScript library that allows us to create interactive, responsive UI by respecting the observer pattern with a clean underlying data model. It is an attempt to bring the Model View View Model [MVVM] feel into JavaScript that offers declarative bindings similar to WPF or Silver light applications. It works on any kind of mainstream browser like IE 6+, Firefox 2+, Chrome, and Safari etc.
Where can we get the knockout library?
We can download Knockout.js file from
here
Key terms of MVVM
Model: It is the storage place of applications data.
View Model: A representation of data and operation to be perform on UI.
View: The interactive UI (say Html or Aspx etc.) that represents the state of the View Model. It closely interacts with the View Model by sending commands whenever an action takes place and updates itself whenever the View Model state changes.
Demonstration
Kindly note that we will use Knockout version 1.2.0 for the demonstration purpose. Let us start with a simple hello world example.
<html>
<head>
<title> Simple hello world example </title>
<script language="javascript" type="text/javascript" src = "knockout-1.2.0.js"></script>
</head>
<body>
<p>Enter a name <input data-bind="value:name"/></p>
<button data-bind="click:buttonCommand">Say hello</button>
<script type="text/javascript">
var viewModel = {
name : ko.observable(""),
buttonCommand : function() {
alert('Hello ' + this.name() + ', welcome to knockout');
}
};
ko.applyBindings(viewModel);
</script>
</body>
</html>
Code Explanation
We have a textbox control as well a button control in the view.
In the View Model, we have two properties namely name and buttonCommand. The buttonCommand is bound to the button control while the name property is to the textbox control. The ko.observable is use to assign the value to the property. The reason is that, the model properties are declared as observables which notifies the subscribers about changes and can automatically detect dependencies. Henceforth, whenever the user enters his/her name in the textbox and clicks on the button, the value that is being assigned to the name property is read and is displayed to the browser.
Also the observable properties need some attention. The values are set or get from the properties through methods. This is to ensure the cross browser compatibility since the getters and setters are not understandable by many browsers.
The data-bind attribute binds the view models properties to the view and the communication sails between these two.
We need to activate Knockout to take effect of the data-bind attribute which is a non native Html attribute. For this reason, we need to call the ko.applyBindings (ViewModel). The first parameter to the applyBindings should be the view model; There is an optional second parameter and if specified should be a DOM node e.g.
ko.applyBindings(viewModel, document.getElementById('ElementID')).
This is very cool right.We will look more into it in some broader fashion in the form of an article.
An Introduction to LINQ for JavaScript(linq.js)
Language integrated query has been introduce into dot net from framework version 3.0. The taste is now available in JavaScript too with linq.js. Currently it supports 90 methods. We can use Enumerable. From (...) to convert an Array to an enumerable and to query them. Moreover it supports intellisence when use with dotnet framework.
Where can we get the LINQ for JavaScript library?
We can download it file from
here
Some simple programs to get ourselves familiar
Let us see the linq.js into action with some simple program
For the first two examples, we will use the below Data Source
var sourceArray1 = ["Niladri Biswas", "Jeeva Baby", "Rudra", "Deepak"];
Example 1: Display names whose length is greater than 10.
Query
Enumerable.From(sourceArray1)
.Where("i => i.length > 10")
.ForEach("i=>alert(i)");
Output
Niladri Biswas and Jeeva Baby as expected
Code Explanation
In Enumerable.From(sourceArray1), we are converting the array into enumerable for further querying.
Where("i => i.length > 10") does the filtering.
ForEach("i=>alert(i)") is where we are looping thru the filtered collection and is printing them.
Example 2: Sort names.
Query
Enumerable.From(sourceArray1)
.OrderBy("o=>o").
ForEach("i=>alert(i)");
Example 3: Given a json datasource, we will first filter the records by CountryName, then ordfer the records by player names and will display them.
DataSource
var jsonArray = [
{ "player": { "id": 1, "PlayerName": "Niladri" }, "CountryName": "India" },
{ "player": { "id": 2, "PlayerName": "Deepak" }, "CountryName": "Australia" },
{ "player": { "id": 3, "PlayerName": "Eshwer" }, "CountryName": "US" },
{ "player": { "id": 4, "PlayerName": "Naina" }, "CountryName": "India" }
Query
Enumerable.From(jsonArray)
.Where("$.CountryName == 'India'")
.OrderBy("$.player.PlayerName")
.Select("$.player.id + '|' + $.player.PlayerName + '|' + $.CountryName")
Jquery.Linq.js
This library also has a jquery extension (jquery.linq.js). As a quick example
$.Enumerable.Range(1, 10).Where("$%2==0").ForEach("alert($)");
Will display the even numbers
Features in Linq for JavaScript are as under
- Implement all .NET 4.0 methods and many extra methods (inspiration from Rx,
Achiral, Haskell, Ruby, etc...)
- Complete lazy evaluation
- Full IntelliSense support for VisualStudio
- Two versions - linq.js and jquery.linq.js (jQuery plugin)
- Support Windows Script Host
- Binding for Reactive Extensions for JavaScript(RxJS) and IntelliSense
Generator
- NuGet install support(linq.js, linq.js-jQuery, linq.js-Bindings)
Hope this gives some insight about the usage of linq.js.
Conclusion
In this short write up we have seen two of the powerful JavaScript libraries that will help us to speed up the client side operations in a more organized manner.
Thanks for reading.