Telerik blogs

We’re dropping so much new awesomeness on you with this beta release that’s it hard to keep up with it all.  One of the more powerful things in the beta is the new MVVM framework.  If you are familiar with MVVM and you have been using Kendo UI, then you have been waiting for this.  And it’s here.

For those not familiar with the term MVVM, lets gets some context and then we’ll jump in and take a look at how to use it.

The Problem

We’ve seen an unprecedented increase in the amount of devices and operating systems in the past few years.  We have desktops, laptops, tablets, phones, netbooks and even devices that connect right to your TV (read Roku, Apple TV).  The only way that you can deliver content on all of these platforms without writing dozens of applications, is to write a web application.  These web applications are becoming more and more complex on the client side.  AJAX is an important part of modern web applications and there is an increasing need to model data in the client as well as on the server. 

You may be familiar with the phrase “Single Page Application”, or an SPA.  The best example of an SPA is probably Gmail.  The idea is that when you visit the application and click on actions, instead of the entire page being sent to the server and then a new page being sent back, only the relevant portion of the UI is changed.  This is done by making background requests for data to the server and then updating the UI.  This can make for very complex scenarios in a UI as you try and keep up with changes that are happening with your data on the server, the data as it’s changed in the UI, and the current overall state of the application.

The Solution

One of the ways that people are handling this is with different architecture patterns on the front-end like MVP, MVC or MVVM.  You may be familiar with BackboneJS, KnckoutJS or EmberJS.  These are all implementations of various patterns which attempt to help you organize and manage your UI while alleviating the need for you to manually keep track of all the changes.

MVVM is short for Model View View-Model.  Kendo UI has a full MVVM framework baked right into it’s core with this beta release.  Lets take a look at how MVVM makes your life more awesome, and how it works seamlessly with Kendo UI.

Note: For those who have been using MVVM and Knockout for some time and have questions about why we decided to make MVVM part of the Kendo UI core, please read this post.

MVVM In Kendo UI

Lets look at a simple scenario and how we might typically build this application, then we’ll back up and engineer it with the MVVM pattern. 

Old School

Have a look at the “old school” way that we might build a simple list application.

This is typical.  Bind the button to an event handler, select the DOM elements, update the table with a new row and then clear the DOM elements back out.  All manually.  The only way we could make this easier is by doing some templating instead of creating the row dynamically with HTML in the JavaScript (which is YUCK btw).

New School

Let’s see how the new MVVM pattern in Kendo UI can really make life easier.

The first thing that we need to do is to create a view model.  A view model is an observable object.  This object has properties and methods.  Each property will be bound to something in the HTML. This binding is two way, meaning that if the binding changes on the UI, the model changes and vice versa.

ViewModel

Here is what the ViewModel looks like.

var viewModel = kendo.observable({
     
     // expenses array will hold the grid values
     expenses: [],
     
     // type array populates the drop down
     type: [{ name: "Food", value: "food"}, { name: "Merchant", value: "merchant"}, { name: "Bills", value: "bills" }],
    
     // expenseType holds the currently selected value of the dropdown list
     expenseType: "food", 
     
     // the values are bound to the merchant and amount fields
     merchant: null,
     amount: null,
    
     // event to execute on click of add button
     create: function(e) {
             
         // add the items to the array of expenses this.get("expenses").push({Type: this.get("expenseType"), 
                                    Merchant: this.get("merchant"), 
                                    Amount: this.get("amount")});
        
        // reset the form this.set("expenseType", "food");
        this.set("merchant", "");
        this.set("amount", "");
    }
        
});

// apply the bindings
kendo.bind(document.body.children, viewModel);
 
 
 

You can see from the comments inline that we have moved some things out of the markup and into the view model.  Lets break it down…

expenses: Instead of using a plain HTML table to display the values from our input form, we are going to use a Kendo UI Grid.  It’s a much better user experience.  The expenses array holds the values that the grid will use as is source.

type: Remember the select element? Instead of defining the items inline with options in the HTML, we are going to bind the element to this array.  We’ll also apply some Kendo UI magic to this boring dropdown.

expenseType: This variable will be bound to whatever value is currently selected in the above mentioned dropdown.

merchant: Bound to the value of the merchant input box.

amount: Bound to the value of amount input box.

create: This is the event that will be fired by the Add button.  Inside the event, we are going to do following:

    1. Update the expenses array with a new item.  We do this by getting the values of the relevant controls.  These controls are bound to view model variables and can be referenced with this.get().
    2. Clear the form out by calling this.set() on each of the view model properties that is bound to a control value.  Because the binding is two-way, setting the value of the model object will also set the value of the bound element.

kendo.bind(document.body.children, viewModel): The statement that initializes the binding between the view model and the relevant HTML.

HTML

We additionally need to make some changes in our markup.  Lets take it element by element and examine the bindings:

<select data-role="dropdownlist" data-bind="source: type, value: expenseType" 
 data-text-field="name" data-value-field="value" ></select>

The select element now has no options.  Instead, it has some new data attributes.

    1. data-role=”dropdownlist”: This tells Kendo UI to make this element into a Kendo UI DropDownList.  No need to initialize the element.  Kendo UI is going to do that for you when kendo.bind is called.
    2. data-bind=”source: type, value: expenseType”: These are the properties in the view model that we are binding the dropdown list to.  The source is where it’s data comes from.  The value specifies which property on the model will be bound to the currently selected value of the dropdown.
    3. data-text-field: The field from the source to use as the text of each item in the dropdown.
    4. data-value-field: The field from the source to use as the value of each item in the dropdown.

 
<dt>Merchant</dt> <dd><input id="merchant" type="text" class='k-textbox' 
                             data-bind="value: merchant" /></dd>

 

The merchant input has a new binding.  The data-bind=”value: merchant” says that we want to bind the value of this input to the merchant variable in the view model.  I aslo added a “k-textbox” css class to it to make it pretty.


 
<dt>Amount</dt> <dd><input data-role="numerictextbox" data-bind="value: amount" 
                           id="amount" type="text" /></dd>

 

The amount input has two new bindings:

    1. data-role=”numerictextbox”: You have probably guessed it by now.  This transforms the input into a Kendo UI Numeric TextBox.
    2. data-bind=”value: amount”: As with the merchant input, this binds the value of the spinner to the amount field in the view model

 
<button id="create" data-bind="click: create" class="k-button">Add</button>

The Add button has only one new change.  It now has a data-bind=”click: create”.  This binds its click event to the create function in the view model.  It’s crazy how easy this is.


 
<div data-role="grid" data-sortable="true" data-bind="source: expenses" 
                      data-columns='["Type", "Merchant", "Amount"]' ></div>

 

This last one is the grid.  Yes, this one line creates a Kendo UI Grid.

    1. data-role=”grid”: By now you know that this defines it as a grid.
    2. data-sortable=”true”: This makes the grid sortable.
    3. data-columns=’[“Type”, “Merchant”, “Amount”]’: This defines the columns that will be in the grid.  Technically, you could leave this line out, but then the grid won’t display any column headers when it’s empty.


 

Finished Product

Here is the finished product.  Kendo UI bindings are keeping the UI and the model in sync as changes are made.

Not only does MVVM keep you from having to worry about many of the manual details, it also dramatically simplifies KendoUIDevicePackyour code so that in your JavaScript you are only working with model objects.  The DOM simply reflects the changes that you make to the model.

Download the beta TODAY and don’t forget to register for the launch webinar March 22nd At 10 AM CST for your chance to win an iPad, a Galaxy Tab, a Blackberry Playbook and an iPod touch. Not just one, but all of them.  All you have to do to be eligible to win is register!

You won’t want to miss all the new things in this release of Kendo UI.  I assure you - I have barely scratched the surface in this post.

About the Author
is a web developer living in Nashville, TN. He enjoys working with and meeting developers who are building mobile apps with jQuery / HTML5 and loves to hack on social API's. Burke works for Telerik as a Developer Evangelist focusing on Kendo UI. Burke is @burkeholland on Twitter.


Comments

Comments are disabled in preview mode.