10. @nishanil
The MVVM Pattern
• Model-View View-Model
• Software architectural design pattern
• Emerged in the 2005 timeframe to support the declarative data binding features of
WPF / XAML
11. @nishanil
Benefits
• Developer/Designer Collaboration without Conflict - Since the UI is void of any
non-visual code such as business logic, the team’s designer can confidently work
on modifying the code without worrying about breaking the programmer’s code.
• Testable Code - Decoupling the view from the view model enables us to write
clean unit tests.
• Code Maintainability - Testable, decoupled code is easier to maintain. A bug can
be found much more easily if there is only one place to inspect.
14. @nishanil
Introducing KnockoutJS
• Knockout is an open source JavaScript library that enables MVVM applications by
implementing binding
• Properties in the Model classes are of type ko.observable
• Observables in JavaScript notify subscribers of property changes
• Supports all major browsers
6+ 2+
15. @nishanil
Comparing JavaScript to WPF
Runtime
CLR - XAML Binding
Business Logic
C#
Presentation
XAML
Window
Runtime
Browser - Knockout
Business Logic
JS
Presentation
HTML
Page
16. @nishanil
Step 1: Reference KO in the View
<script type="text/javascript" src="../scripts/ko/knockout-
2.1.0.js"></script>
17. @nishanil
Step 2: Associate the View Model with the View
<script>
$(document).ready(function () {
// Instantiate the CustomerViewModel model and apply bindings
var customerViewModel = new CustomerViewModel();
ko.applyBindings(customerViewModel);});
</script>
19. @nishanil
Understanding Bindings
• Bindings are declared in the visual element mark-up by using the data-bind
attribute.
• These bindings are associated with view model properties that are known as
observables.
• Observables are properties that will automatically issue notifications whenever
their value changes.
function CustomerViewModel() {
var self = this;
// Properties
self.customers = ko.observableArray();
20. @nishanil
Knockout Bindings
• foreach: Lets you iterate through a loop and apply the same markup to each item
in the list. This is used to render the to-do lists and to-do items. Within the
foreach, the bindings are applied to the elements of the list.
• visible: Used to toggle visibility. Hide markup when a collection is empty, or make
the error message visible.
• value: Used to populate form values.
• click: Binds a click event to a function on the view model.
23. @nishanil
What is a SPA?
“Single-page application” (SPA) is the
general term for a web application that
loads a single HTML page and then
updates the page dynamically, instead
of loading new pages. After the initial
page load, the SPA talks with the
server through AJAX requests.