Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
KnockoutJS Web Development

You're reading from  KnockoutJS Web Development

Product type Book
Published in Feb 2015
Publisher
ISBN-13 9781782161028
Pages 178 pages
Edition 1st Edition
Languages

Chapter 2. Using Arrays, Nesting, and Grids

Now we've had a taste of KnockoutJS, we are now ready to learn new coding skills. In this chapter, we will see how to extend our MVVM skills to make a lot more sweet data interaction experiences. This chapter will focus on:

  • Conditional binding

  • Simpler nested binding

  • Observable arrays

  • Paged grids

  • Sorting data collections

Conditional binding


Data binding is the essence of many new libraries that interact with the HTML markup as it gets converted to the DOM. We saw binding in Chapter 1, Getting Started with KnockoutJS, using the data-bind ="..." bindings. Here we will be looking at conditional binding.

The first thing we will do is understand the concept of conditional binding. Our example is meant to be conceptual. We will show a more practical example shortly in this chapter.

The if binding plays a very similar role to the visible property in the DOM. The difference is that the if binding actually adds and removes the content from the DOM whereas visible swaps the CSS display style between visible and none.

Create a new file by copying the _base.htm file, located in the ko_2/do folder, and naming it condition.htm within the do folder. If you get stuck, there is a completed copy inside the done folder. To make things look better, we will now be using the larger Bootstrap template base as it will give us better...

Introduction to arrays in Knockout


We will start by working with an unbound array. You will see that Knockout is smart enough to still work with the array and display the contents correctly. In fact, the array we will start out with will be an array with nested data. Add the highlighted data to the script section of our page:

myVM = {
showDetails: ko.observable(false),
employee: [
{name:"John Jones", spouse: { name: "Mary Jones"}},
{name:"Bill Williams", spouse: null},
{name:"Sandy Rivers", spouse: { name: "Mark Rivers"}},
]
}

The employee array data will automatically bind to the MVVM system when we run our applyBindings function on the page. We will need some markup to tell us that it has actually worked. I suggest separating the section of content on the page using the <hr/> tag just for clarity. Now add the following code to the markup section:

<ul data-bind="foreach: employee">
    <li>Employee: <strong data-bind="text:name"></strong>
        <div data...

Sorting time


Displaying data is a very common use case for web pages. Perhaps the most common function people perform on data besides searching is sorting. We are going to look at how to sort data based on particular data fields. This time, we will create the logic first. Enter the following code into the script tag:

function doSort() {
    myVM.employee.sort(function (left, right) {
        return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1);
    });
}

We will break down the logic for those unfamiliar with this level of JavaScript:

  1. The sort function passes in two structures. Each structure matches the items being sorted. The variable name could be anything; we choose left and right because it helps the programmer remember which variable is which. You can use, of course, any variable naming you choose. Each variable contains the whole structure of the item being passed in.

  2. The basic return value for sort needs to be true or false. This tells the program whether the two...

The simpleGrid plugin


Just like jQuery allows for custom plugins, it is possible to use plugins with Knockout as well. Here, we are going to use a simple plugin to add grid functionality to our page. This plugin also smartly adds paging to the page. We will also do some simple CSS to set our grid so it loosens up the space between the cells in the table.

Tip

The reason we code with jQuery, KnockoutJS, Bootstrap, and other Don't Repeat Yourself (DRY) libraries is that they package our work. We don't have to rethink, recode, or repeat our work when this is done. Using solutions such as jQuery and KnockoutJS, we can DRY out our code by adding our own library extensions. The simple grid plugin is an example of this.

Note that we will cover enough detail in this book that by the end you should be able to modify this plugin or build your own. However, you will have to understand JavaScript, CSS, HTML, and other topics enough to get the job you are seeking to DRY out. Regarding KnockoutJS, you will...

Summary


If you have ever built any JavaScript pages with this much interaction with your data using JavaScript or even with jQuery, then you will know why the library deserves the title of Knockout. The amount of power we have gained using this library in just two chapters is compelling. Through this chapter you should have gained the ability to do conditional binding, nested binding, observable array collections, adding and deleting records in array style management, and sorting observable arrays. You even got a quick look at a Knockout plugin.

In the next chapter, we will learn to drive web forms with the power of Knockout. They think differently; and for a few, that is the first reaction. It is an interesting double take as the second reaction that nearly instantly follows is that it is better. Event binding is also a topic we will dig into in the next chapter with special focus on the over-the-top punch Knockout gives us when dealing with grid forms.

lock icon The rest of the chapter is locked
You have been reading a chapter from
KnockoutJS Web Development
Published in: Feb 2015 Publisher: ISBN-13: 9781782161028
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}