Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to Knockout.js With Play Template

DZone's Guide to

Introduction to Knockout.js With Play Template

In this article, we discuss the basics of Knockout.js, and demonstrate how it can be used to enhance your site's UI using the ViewModel.

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

Knockout is a JavaScript library that is based on Model–View–Viewmodel (MVVM) that helps to build responsive UI displays. This makes a clear separation between the mode l(Domain model/stored data), view (User Interface) and view-model (presentation of the model in which a 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 elements 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 builds a connection between ViewModel and View, and if any update takes place it will automatically update the UI element.

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

Let's Get Started With Knockout.js:

1. A little obvious here, but the first thing you need to download and include is Knockout.js itself.

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

2.To create a Scala case class for the Domain Model and a controller action for the default data, use the below code:

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. To create a play template for the "user_information.scala.html"

data-bind syntax, link your data to your HTML. This should consist of 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 the ViewModel:

Create the view model (UserDetailModel) properties as observables. This is a JavaScript object that notifies subscribers about the changes and automatically detects their dependencies. Here, Knockout provides a way to link the data model to the 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 the demo code from here.

I hope this blog is helpful to you!

Thanks!

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:
web dev ,knockout.js ,mvvm

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}