Skip to main content
Version: 2.2.0

Creating a View

Key Points
  • Durandal renders modules with views.
  • Create a view by adding an html file to your application.
  • Views should have one root element.
  • The view locator matches views to your modules.
  • Use knockout bindings to synchronize a view with its module. :::

A Simple Example​

Views are html fragments, which typically contain data-binding expressions. These binding expressions declare how the module and the view are connected and kept in sync. So, when a property changes in the model, the DOM updates. Or, when a user interacts with or inputs information through the DOM, the model updates.

Let's imagine we have a simple customer list module that we want to display.

customerList.js
define(function (require) {
var backend = require("backend");

return {
customers: ko.observableArray([]),
activate: function () {
var that = this;
return backend.getCustomers().then(function (results) {
that.customers(results);
});
},
};
});
customerList.html
<div>
<h2>Customers</h2>
<ul data-bind="foreach: customers">
<li data-bind="text: fullName"></li>
</ul>
</div>

There are a few noteworthy details in this example.

  1. Knockout is used to declare bindings between the module and the view.
  2. The view has exactly one root element. Durandal requires this. If comments are found at the root, they will be removed. In the case where more than one root element is found, they will be wrapped in a div.
  3. The customerList.js and customerList.html are paired together by convention. For more information on how that works, or how to customize this behavior, see the documentation on View Location & Customization.