Docsity

Introdução à Criação de Interfaces de Usuário Dinâmicas com Knockout.js, Manuais, Projetos, Pesquisas de Cultura

Pré-visualização parcial do texto

Baixe Introdução à Criação de Interfaces de Usuário Dinâmicas com Knockout.js e outras Manuais, Projetos, Pesquisas em PDF para Cultura, somente na Docsity!

By

Ryan Hodson

Foreword by Daniel Jebaraj

Table of Contents

  • The Story behind the Succinctly Series of Books
  • About the Book
  • Introduction
    • Other Features
      • Pure JavaScript
      • Extensible
      • Utility Functions
    • What Knockout.js is Not
  • Chapter 1 Conceptual Overview
    • Observables
    • Bindings
    • Summary
  • Chapter 2 Hello, Knockout.js
    • Download Knockout.js................................................................................................
    • The HTML
    • Defining the ViewModel
    • Binding an HTML Element
    • Observable Properties
      • Accessing Observables
    • Using Custom Objects
    • Interactive Bindings
    • Summary
  • Chapter 3 Observables
    • Computed Observables
    • Observable Arrays
      • Adding Items
      • Deleting Items
      • Destroying Items
      • Other Array Methods...............................................................................................
    • Summary
  • Chapter 4 Control-Flow Bindings..............................................................................
    • The foreach Binding
    • Working with Binding Contexts
      • The $root Property
      • The $data Property
      • The $index Property
      • The $parent Property
    • Discounted Products
    • The if and ifnot Bindings
    • The with Binding
    • Summary
  • Chapter 5 Appearance Bindings
    • The text Binding
    • The html Binding
    • The visible Binding
    • The css Binding
    • The style Binding
    • The attr Binding..........................................................................................................
    • Summary
  • Chapter 6 Interactive Bindings
    • An HTML Form
    • The click Binding
    • The value Binding
    • The event Binding
      • Event Handlers with Custom Parameters................................................................
    • The enable/disable Bindings
    • The checked Binding..................................................................................................
      • Simple Check Boxes
      • Check-box Arrays
      • Radio Buttons
    • The options Binding
      • Using Objects as Options
    • The selectedOptions Binding
    • The hasfocus Binding.................................................................................................
    • Summary
  • Chapter 7 Accessing External Data
    • A New HTML Form
    • Loading Data..............................................................................................................
    • Saving Data
    • Mapping Data to ViewModels
    • Summary
  • Chapter 8 Animating Knockout.js
    • Return of the Shopping Cart.......................................................................................
    • List Callbacks
    • Custom Bindings
    • Summary
  • Chapter 9 Conclusion
  • Appendix A

The Story behind the Succinctly Series

of Books

Daniel Jebaraj, Vice President Syncfusion, Inc.

taying on the cutting edge

As many of you may know, Syncfusion is a provider of software components for the Microsoft platform. This puts us in the exciting but challenging position of always being on the cutting edge.

Whenever platforms or tools are shipping out of Microsoft, which seems to be about every other week these days, we have to educate ourselves, quickly.

Information is plentiful but harder to digest

In reality, this translates into a lot of book orders, blog searches, and Twitter scans.

While more information is becoming available on the Internet and more and more books are being published, even on topics that are relatively new, one aspect that continues to inhibit us is the inability to find concise technology overview books.

We are usually faced with two options: read several 500+ page books or scour the web for relevant blog posts and other articles. Just as everyone else who has a job to do and customers to serve, we find this quite frustrating.

The Succinctly series

This frustration translated into a deep desire to produce a series of concise technical books that would be targeted at developers working on the Microsoft platform.

We firmly believe, given the background knowledge such developers have, that most topics can be translated into books that are between 50 and 100 pages.

This is exactly what we resolved to accomplish with the Succinctly series. Isn’t everything wonderful born out of a deep desire to change things for the better?

The best authors, the best content

Each author was carefully chosen from a pool of talented experts who shared our vision. The book you now hold in your hands, and the others available in this series, are a result of the authors’ tireless work. You will find original content that is guaranteed to get you up and running in about the time it takes to drink a few cups of coffee.

Free forever

Syncfusion will be working to produce books on several topics. The books will always be free. Any updates we publish will also be free.

S

About the Book

This book is intended for professional web developers who need to build dynamic, scalable user interfaces with minimal markup. Basic knowledge of HTML, CSS, and JavaScript is assumed. Experience with any particular JavaScript framework (e.g., jQuery, Prototype, MooTools, etc.) is not strictly required, though it wouldn’t hurt.

The first two chapters provide a brief overview of the Knockout.js library. Chapter 3 discusses the data-oriented aspects of Knockout.js, and then Chapters 4 through 6 show you how to connect this data to HTML elements. The last two chapters of this book use jQuery’s AJAX functionality to demonstrate how Knockout.js interacts with server-side applications and jQuery’s animation features to add some flare to our data-driven interfaces. If you’ve never used jQuery before, don’t worry—the examples are easily adapted to other frameworks.

Introduction

Creating data-driven user interfaces is one of the most complex jobs of a web developer. It requires careful management between the interface and its underlying data. For example, consider a simple shopping-cart interface for an e-commerce website. When the user deletes an item from the shopping cart, you have to remove the item from the underlying data set, remove the associated element from the shopping cart’s HTML page, and update the total price. For all but the most trivial of applications, figuring out which HTML elements rely on a particular piece of data is an error-prone endeavor.

Figure 1: Manually tracking dependencies between HTML elements and their underlying data

The Knockout.js JavaScript library provides a cleaner way to manage these kinds of complex, data-driven interfaces. Instead of manually tracking which sections of the HTML page rely on the affected data, Knockout.js lets you create a direct connection between the underlying data and its presentation. After linking an HTML element with a particular data object, any changes to that object are automatically reflected in the DOM.

Figure 2: Automatically tracking dependencies using Knockout.js

Utility Functions

Knockout.js comes with several utility functions, including array filters, JSON parsing, and even a generic way to map data from the server to an HTML view. These utilities make it possible to turn large amounts of data into a dynamic user interface with just a few lines of code.

What Knockout.js is Not

Knockout.js is not meant to be a replacement for jQuery, Prototype, or MooTools. It doesn’t attempt to provide animation, generic event handling, or AJAX functionality (however, Knockout.js can parse the data received from an AJAX call). Knockout.js is focused solely on designing scalable, data-driven user interfaces—how that underlying data is obtained is completely up to you.

Figure 4: Knockout.js supplementing a full web application stack

This high level of specialization makes Knockout.js compatible with any other client-side and server-side technology, but it also means Knockout.js often requires the cooperation of a more full-featured JavaScript framework. In this sense, Knockout.js is more of a supplement to a traditional web application stack, rather than an integral part of it.

Chapter 1 Conceptual Overview

Knockout.js uses a Model-View-ViewModel (MVVM) design pattern, which is a variant of the classic Model-View-Controller (MVC) pattern. As in the MVC pattern, the model is your stored data, and the view is the visual representation of that data. But, instead of a controller, Knockout.js uses a ViewModel as the intermediary between the model and the view.

The ViewModel is a JavaScript representation of the model data, along with associated functions for manipulating the data. Knockout.js creates a direct connection between the ViewModel and the view, which is how it can detect changes to the underlying data and automatically update the relevant aspects of the user interface.

Figure 5: The Model-View-ViewModel design pattern

The MVVM components of our shopping cart example are listed as follows:

Model: The contents of a user’s shopping cart stored in a database, cookie, or some other persistent storage. Knockout.js doesn’t care how your data is stored—it’s up to you to communicate between your model storage and Knockout.js. Typically, you’ll save and load your model data via an AJAX call.  View: The HTML/CSS shopping cart page displayed to the user. After connecting the view to the ViewModel, it will automatically display new, deleted, and updated items when the ViewModel changes.  ViewModel: A pure-JavaScript object representing the shopping cart, including a list of items and save/load methods for interacting with the model. After connecting your HTML view with the ViewModel, your application only needs to worry about manipulating this object (Knockout.js will take care of the view).

Observables

Knockout.js uses observables to track a ViewModel’s properties. Conceptually, observables act just like normal JavaScript variables, but they let Knockout.js observe their changes and automatically update the relevant parts of the view.

Chapter 2 Hello, Knockout.js

This chapter is designed to be a high-level survey of Knockout.js’ main components. By implementing a concrete sample application, we’ll see how Knockout’s ViewModel, view, observables, and bindings interact to create a dynamic user interface.

First, we’ll create a simple HTML page to hold all of our code, then we’ll define a ViewModel object, expose some properties, and even add an interactive binding so that we can react to user clicks.

Download Knockout.js

Before we start writing any code, download the latest copy of Knockout.js from the downloads page at GitHub.com. As of this writing, the most recent version is 2.1.0. After that, we’re ready to add the library to an HTML page.

Samples

The samples in this book are available at https://bitbucket.org/syncfusion/knockoutjs_succinctly.

The HTML

Let’s start with a standard HTML page. In the same folder as your Knockout.js library, create a new file called index.html, and add the following. Make sure to change knockout-2.1.0.js to the file name of the Knockout.js library you downloaded.

Sample code: item1.htm

Hello, Knockout.js

Hello, Knockout.js

Bill's Shopping Cart

This is a basic HTML 5 webpage that includes the Knockout.js library at the bottom of ; although, like any external script, you can include it anywhere you want (inside is the other common option). The style.css style sheet isn’t actually necessary

for any of the examples in this book, but it will make them much easier on the eyes. It can be found in Appendix A, or downloaded from https://bitbucket.org/syncfusion/knockoutjs_succinctly. If you open the page in a web browser, you should see the following:

Figure 8: Basic webpage

Defining the ViewModel

Since we’re not working with any persistent data yet, we don’t have a model to work with. Instead we’ll skip right to the ViewModel. Until Chapter 7, we’re really just using a View-ViewModel pattern.

Figure 9: Focusing on the view and ViewModel for the time being

Remember, a ViewModel is a pure JavaScript representation of your model data. To start out, we’ll just use a native JavaScript object as our ViewModel. Underneath the

Knockout.js won’t automatically update the view, and the page will still read “John’s Shopping Cart.” This is because we haven’t exposed the firstName property to Knockout.js. Any properties that you want Knockout.js to track must be observable. We can make our ViewModel’s properties observable by changing personViewModel to the following:

Sample code: item3.htm

var personViewModel = { firstName: ko.observable("John"), lastName: ko.observable("Smith") };

Instead of directly assigning values to firstName and lastName, we use ko.observable() to add the properties to Knockout.js’ automatic dependency tracker. When we change the firstName property, Knockout.js should update the HTML element to match:

ko.applyBindings(personViewModel); personViewModel.firstName("Ryan");

Accessing Observables

You’ve probably noticed that observables are actually functions—not variables. To get the value of an observable, you call it without any arguments, and to set the value, you pass the value as an argument. This behavior is summarized as follows:

Getting: Use obj.firstName() instead of obj.firstName  Setting: Use obj.firstName("Mary") instead of obj.firstName = "Mary"

Adapting to these new accessors can be somewhat counterintuitive for beginners to Knockout.js. Be very careful not to accidentally assign a value to an observable property with the = operator. This will overwrite the observable, causing Knockout.js to stop automatically updating the view.

Using Custom Objects

Our generic personViewModel object and its observable properties work just fine for this simple example, but remember that ViewModels can also define methods for interacting with their data. For this reason, ViewModels are often defined as custom classes instead of generic JavaScript objects. Let’s go ahead and replace personViewModel with a user-defined object:

Sample code: item4.htm

function PersonViewModel() { this.firstName = ko.observable("John");

this.lastName = ko.observable("Smith"); }; ko.applyBindings(new PersonViewModel());

This is the canonical way to define a ViewModel and activate Knockout.js. Now, we can add a custom method, like so:

function PersonViewModel() { this.firstName = ko.observable("John"); this.lastName = ko.observable("Smith"); this.checkout = function() { alert("Trying to check out!"); }; };

Combining data and methods in a single object is one of the defining features of the MVVM pattern. It provides an intuitive way to interact with data. For example, when you’re ready to check out simply call the checkout() method on the ViewModel. Knockout.js even provides bindings to do this directly from the view.

Interactive Bindings

Our last step in this chapter will be to add a checkout button to call the checkout() method we just defined. This is a very brief introduction to Knockout.js’s interactive bindings, but it provides some useful functionality that we’ll need in the next chapter. Underneath the

tag, add the following button:

Checkout

Instead of a text binding that displays the value of a property, the click binding calls a method when the user clicks the element. In our case, it calls the checkout() method of our ViewModel, and you should see an alert message pop up.

Figure 11: Alert message created after clicking the Checkout button

Knockout.js’ full suite of interactive bindings will be covered in Chapter 6.