Introduction to Knockout js with Play template


Knockout is a JavaScript library that is based on Model–view–viewmodel (MVVM) that helps to build responsive UI display. This makes a clear separation between the model(Domain model/ stored data), view(User Interface) and view-model(presentation of the model in which binder communicates between view and data-binder).

Why Knockout js?

1. Declarative bindings: This is a convenient way to bind the Html to the data model. When we try to manipulate the DOM with the declarative binding all the bounded element remain connected

2.Dependency Tracking: Whenever you modify or update your data model, It will automatically update the associated UI.

3.MVVM Design Pattern: knockout build a connection between ViewModel and View, and if any update takes place it will automatically update the UI element.

4.Extensible – This implements custom behaviours as new declarative bindings for easy reuse in just a few lines of code.

5. and much more

let’s start with Knockout js:

1. The first thing you need to download and include knockout js.

'text/javascript' src='knockout-3.4.0.js'>

2. Creating a Scala case class for Domain Model and controller action for default data:

case class User(firstName: String,
                lastName: String,
                email: String)
def userDetail = Action {
  implicit val userInfo = new Writes[User] {
    def writes(user: User) = Json.obj(
      "firstName" -> user.firstName,
      "lastName" -> user.lastName,
      "email" -> user.email
    )
  }
  val user = Json.toJson(User("testfirst", "testLast", "test@example.com"))
  Ok(user)
}

3. Creating play template “user_information.scala.html”.

data-bind syntax, link data to Html, consists two items: binding name and value

<div class="row">
<div class="col-md-12" >
<div class="form-group">
<label>First Name:</label>
<input data-bind="value: firstName"/></div>
<div class="form-group">
<label>Last Name:</label>
<input data-bind="value: lastName"/></div>
<div class="form-group">
<label>Email:</label>
<input data-bind="value: email"/></div>
</div>
<h2>User Detail, <span data-bind="text: userDetail"> </span>!</h2>
</div>

4.Creating ViewModel:

create view model(UserDetailModel) properties as observables, it’s a Javascript object that notifies subscribers about the changes and automatically detects their dependencies. Here, ko provides a way to link data model to UI.

var UserDetailModel = function (data) {
    this.firstName = ko.observable(data.firstName);
    this.lastName = ko.observable(data.lastName);
    this.email = ko.observable(data.email);
    // Knockout resolved dependencies automatically. It knows that userDetail depends on firstName and lastName and email.

    this.userDetail = ko.pureComputed(function() {
        return this.firstName() + " " + this.lastName() + " " + this.email();
    }, this);
};

$(document).ready(function(){
    var request = $.ajax({
        url: "/user",
        type: "GET",
        contentType: "text/plain",
        success: function (data) {
            ko.applyBindings(new UserDetailModel(data))
        }
    });
});

Get demo code from here

I hope this blog is helpful to you!

Thanks

About teenaVashist

Teena is a Software Consultant at Knoldus Software LLP having 2 year experience working in Scala. She is very enthusiastic towards her work and good at working in team. She is very much keen to learn new technologies. She is familiar with programming language's such as Scala, Css, Javascript, HTML, Java. She likes reading novels and watching movies.
This entry was posted in JavaScript, Play 2.4.X, Play Framework, Scala and tagged , , . Bookmark the permalink.

One Response to Introduction to Knockout js with Play template

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 )

Google+ photo

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

Connecting to %s