Declarative Bindings in JavaScript Windows Metro Style Apps

Here you will see how you can work with binding data declaratively in JavaScript Windows Metro style apps.

Basically we have two types of binding in JavaScript Windows Metro style apps; they are:

  • Declarative Bindings
  • Dynamic Bindings

Declarative Bindings

Binding in JavaScript Windows Metro style apps is easy and straightforward, it is a mechanism by which you include data from your view model in the HTML that is displayed to the user, and the way data is displayed is separated from the management of the data. A connection, or binding, between the UI and a data object allows data to flow between the two. When a binding is established and the data changes, the UI elements that are bound to the data can display changes automatically.

Declarative-Bindings.jpg

A data binding consists of a target and a source. The target is usually a property of a control, and the source is usually a property of a data object.

Here in this article I will explain about Declarative Bindings.

Declarative Bindings

In this type of binding you include details of the view model data directly in your HTML markup.

Example

In a Metro JavaScript file the ViewModel.UserData object will contain the data that is specific to the user.

Step 1: Now add some statements to define the data in the viewmodel.js file as in the following:

ViewModel.UserData.username = "Surjeet";

Step 2: Now add a script element in the HTML document to provide the reference of the js file as in the following:

<script src="/js/viewmodel.js"></script>

Step 3: Create an HTML file and bind that data to the control as in the following:

<div class="win-type-large">
                User Name:
               
<span data-win-bind="innerText: UserData.username"></span>
            </div>

Step 4: Now tell the WinJS API about the binding attributes so that it can search them and proceed. First create an initial setup JavaScript function. Under this function pass the viewmodel as in the following:

function InitialSetup(e) {

        WinJS.Binding.processAll(document.body, ViewModel);

    }

Step 5: Now pass the InitialSetup() function with the eventObject to the app activation state as in the following:

app.onactivated = function (eventObject) {

        if (eventObject.detail.kind ===

        Windows.ApplicationModel.Activation.ActivationKind.launch) {

            if (eventObject.detail.previousExecutionState !==

            Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {

                InitialSetup(eventObject);

            } else {

                //……

            }

            WinJS.UI.processAll();

        }

    };


Step 6: Now when you run your application the bound user name will be displayed like:

Result-Declarative-Bindings.jpg
 


Similar Articles