Using MVVM with HTML5 and JavaScript

The MVVM pattern is an excellent pattern for separating the UI or View and the Code or ViewModel and Model.

With Knockout.js the MVVM pattern can be used with HTML5.

Previously I wrote this post: Using jQuery to enable/disable a button based a text box

This same thing could be done using binding and the MVVM pattern, with jQuery and Knockout.js.

Here is a single file example of using knockout.js and with databinding.

<!-- Step 1a - Create the HTML File or the View -->
<!DOCTYPE html>
    <!-- Step 2 - Include jquery and knockout -->
    <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="scripts/knockout-2.2.1.js"></script>
    <!-- Step 3 - Add script to run when page loads -->
    <script type="text/javascript" >
            <!-- Step 4 - Create a ViewModel -->
            function BasicViewModel() {
                <!-- Note: In this case the model is just a string and a bool -->
                <!-- Step 5 - Create a text property to bind the text to -->
                this.text = ko.observable('');
                <!-- Step 6 - Create a bool property to bind the button enabled state to -->
                this.canClick = ko.computed(function() {
                    return this.text() != null && this.text() != '';  
                    }, this);
            <!-- Step 7 -  Activates knockout.js bindings -->
          ko.applyBindings(new BasicViewModel());

    <!-- Step 8 - Create a HTML Elements with bindings -->
    <input data-bind="value: text, valueUpdate:'afterkeydown'" />
    <button type="button" id="btnEnter" data-bind="enable: canClick">Enter</button>

Anyone who knows MVVM will surely realize that while this example is all in a single file, it is likely that you will have a separate viewmodel javascript file in a production environment.

One Comment

  1. [...] See a MVVM version of this here: Using MVVM with HTML5 and JavaScript [...]

Leave a Reply

How to post code in comments?