Knockout.JS Essentials - Jorge Ferrando - E-Book

Knockout.JS Essentials E-Book

Jorge Ferrando

0,0
32,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

If you are a JavaScript developer who has been using DOM manipulation libraries such as Mootools or Scriptaculous, and you want go further in modern JavaScript development with a simple and well-documented library, then this book is for you. Learning how to use Knockout will be perfect as your next step towards building JavaScript applications that respond to user interaction.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 223

Veröffentlichungsjahr: 2015

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

KnockoutJS Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Refreshing the UI Automatically with KnockoutJS
KnockoutJS and the MVVM pattern
A real-world application – koCart
Installing components
The view-model
The view
The model
Observables to refresh the UI automatically
Managing collections with observables
Inserting elements in collections
Computed observables
Summary
2. KnockoutJS Templates
Preparing the project
Creating templates
The header template
The catalog template
The add-to-cart-modal template
The cart-widget template
The cart-item template
The cart template
The order template
The finish-order-modal template
Handling templates with if and ifnot bindings
Managing templates with jQuery
Managing templates with koExternalTemplateEngine
Summary
3. Custom Bindings and Components
Custom bindings
The toggle binding
The currency binding
Create a binding to debug – the toJSON binding
Being semantic with our bindings
Wrapping a jQuery plugin into a custom binding
Components – isolated view-models
Advanced techniques
Controlling descendant bindings
Using virtual elements
Preprocessing data before binding
Summary
4. Managing KnockoutJS Events
Event-driven programming
The click event
Passing more parameters
Allowing the default click action
Event bubbling
Event types
Event binding
Unobtrusive events with jQuery
Delegation pattern
Building custom events
Events and bindings
Summary
5. Getting Data from the Server
REST services
Defining CRUD
Singleton resources
Setting CRUD operations in the resource
Using resources in the view-model
Using Mockjax to mock HTTP requests
Generating mock data with MockJSON
Retrieving a product by ID
Creating a new product
Separation of concerns – behavior and data
Creating the product service
Creating the CartProduct service
Updating a product
Deleting a product
Sending the order to the server
Handling AJAX errors
Validating data
Extending the product model
Extending the customer model
Summary
6. The Module Pattern – RequireJS
Installing the Knockout context debugger extension
The console
The module pattern
Creating the Shop module
The ViewModel module
The Models module
The Resources module
The Services module
Events, bindings, and Knockout components
Updating the add-to-cart-button component
Updating events
Using RequireJS to manage dependencies
Updating the template engine
Configuring RequireJS
Using RequireJS in our project
Defining the app.js file
Converting a normal module into an AMD module
Applying RequireJS to components
Applying RequireJS to mocks
Applying RequireJS to bindings
Applying RequireJS to events
The limits of the application
Summary
7. Durandal – The KnockoutJS Framework
Installing Durandal
Durandal patterns
The index.html file
The main.js file
The shell view-model
The shell view
Durandal life cycle
The activation life cycle
The promise pattern
Compositions
Object composition
Visual composition
Router
Route parameters
Triggering navigation
Child routers
Events
Widgets
Setting up widgets
Writing the widget view
Writing the widget view-model
Registering the widget
Building a page with Durandal
Summary
8. Developing Web Applications with Durandal – The Cart Project
Introduction
Setting up the project
Routing the project – the shell view-model
The navigation and shell templates
The catalog module
The catalog view
The catalog view-model
The cart service
The log service
Adding products to the catalog
The add product view
The edit view
The add product view-model
Making mocks real
The edit view-model
The cart module
The cart view
The cart view-model
The order module
The order view
The order view-model
Grouping code by feature – managing big projects
Summary
Index

KnockoutJS Essentials

KnockoutJS Essentials

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2015

Production reference: 1210215

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78439-707-4

www.packtpub.com

Credits

Author

Jorge Ferrando

Reviewers

Bhoomi Desai

Christian Droulers

Magesh Kuppan

Commissioning Editor

Dipika Gaonkar

Acquisition Editor

Owen Roberts

Content Development Editor

Shubhangi Dhamgaye

Technical Editor

Ruchi Desai

Copy Editors

Puja Lalwani

Laxmi Subramanian

Project Coordinator

Harshal Ved

Proofreaders

Simran Bhogal

Safis Editing

Paul Hindle

Indexer

Monica Ajmera Mehta

Graphics

Disha Haria

Production Coordinator

Nilesh R. Mohite

Cover Work

Nilesh R. Mohite

About the Author

Jorge Ferrando is a frontend developer at Uni Micro AS, Norway. He develops economy systems using JavaScript. He has experience as a PHP and C# developer working for companies such as Vigilant and Dreamstar Cash.

Jorge grew up in Callosa d'en Sarrià, Spain. He attended the University of Alicante where he discovered that web applications are his passion. He started to develop websites when he was 16 years old for a little company in his hometown. He then started practicing at Vigilant as a junior PHP developer; there, he created his first full web application and discovered the potential of JavaScript. Hard work lead him to a bigger company, Dreamstar Cash, also as a PHP developer. There, he got to know several good developers and began to work more and more with JavaScript; thanks to the company, who wanted to use Node.js, Jorge fell in love with JavaScript and frontend development. A few months later, he moved to Norway with his girlfriend and began to work with a company that gave him new challenges every day, working with KnockoutJS, AngularJS, and Twitter Bootstrap.

Acknowledgments

I can't believe how fortunate I was to work on this book with so many great people. I would like to say thank you to Ellen Bishop, who gave me the opportunity to write it, and Owen Roberts and Shubhangi Dhamgaye, who have led me in my first adventure as a writer. Also to Christian Droulers, I have learned very much with his reviews.

Firstly, I would like to say thank you to my family; they have always supported my dreams and have given me the freedom to fail and succeed by myself, and they have always been by my side taking care of me.

To my girlfriend, Teresa, who supported me in those hard days when I thought all is going to fall because I had work all around and just 24 hours in a day. She is my stone and my stability.

I would like to extend my gratitude to all the people I have learned something from: Manuel Ciges, who gave me the responsibility of making a full production application, and Marcos Fernández, my partner through that trip at Vigilant. Rafael Crisanto from Rc Informática, who gave me my first opportunity as a web developer. Pedro García, Pablo Deeleman, Javier Gómez, Fran Iruela, and Alfonso Fernández, my partners at Dreamstar Cash. Guys you made that time the best of my life and you have made me a better developer.

About the Reviewers

Bhoomi Desai is a technical enthusiast and is always keen to learn new technologies. She specializes in providing solutions for the cloud and web stacks. She is a software engineer by qualification and is yearning to become a software craftsman.

Bhoomi has strong technical expertise in coding standards, design patterns, refactoring, and UI design. She is a specialist in the JavaScript stack, Windows Azure, Amazon AWS, Node.js, and architectural patterns. Bhoomi is an early-curve technology adopter and an enthusiast for Agile and Lean development practices.

I would like to thank my husband for always encouraging me to try new things in life.

Christian Droulers is a young and dynamic software developer who started programming in college and has not stopped since. Always on the lookout for interesting techniques and new patterns to apply in his everyday work, he's passionate about beautiful, clean, and efficient code.

He started his career developing key software applications for SherWeb, a renowned Microsoft hosting partner. Christian's passion and ability to decompose systems effectively led him to a software architect role, where he oversaw the complete rewrite of SherWeb's main application with asynchronous messaging, distributed systems, and recent frontend technologies.

Christian enjoys new challenges. In 2012, he joined up with three friends and cofounded Invup, a start-up aiming to help organizations track and quantify philanthropy. The start-up participated in the MassChallenge competition and came in as a finalist for the quality and innovative nature of their start-up. The company has now closed and the code is open sourced on Bitbucket.

He's currently working for the software consulting firm Vooban, heading a team of six developers working on a new platform for insurance management. He's also the author of a few public projects that are freely available at http://cdroulers.com/projects/. For Christian, software developing is not just a job; it's also a hobby and a way of life.

Magesh Kuppan is a freelance consultant and trainer on web technologies with over 17 years of experience. Everything about technology excites him.

I am grateful to my parents, without whom I would not be what I am today. I am also thankful to my wife for she has been instrumental in all my efforts. Thanks to my little son who brings bliss to my life.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

One of the hardest problems to solve when we build the user interface is to synchronize data that developers manage behind the scenes, in the code, and data that is shown to the user. The first step that developers made was to separate the presentation and the logic. That separation allowed developers to manage both sides better and separately. But communication between these two layers still became hard. That was because JavaScript was considered a non-important language and we used to use it just for validation. Then jQuery gave us a clue about how powerful this language could be. But still data was managed in the server and we just displayed static presentations. That makes the user experience poor and slow.

Over the last few years, a new kind of architectural pattern has emerged. It is called the MVVM pattern. Libraries and frameworks that use this kind of pattern make it easy for developers to synchronize views and data. One of these libraries is Knockout, and the framework that uses Knockout is named Durandal.

Knockout is a fast and cross-browser-compatible library that helps us to develop client-side applications with a better user experience.

Developers don't need to worry any more about data synchronization. Knockout binds our code to the HTML elements showing the state of our code to the user in real time.

This dynamic binding makes us forget about coding synchronization, and we can focus our effort on coding the important features of our application.

Nowadays, managing these kinds of frameworks is a must for front-end developers. In this book, you will learn the basics of Knockout and Durandal and we will go into the best design practices and patterns of JavaScript.

If you want to improve the user experience of your applications and create fully operative frontend applications, Knockout and Durandal should be your choice.

What this book covers

Chapter 1, Refreshing the UI Automatically with KnockoutJS, teaches you about the Knockout library. You will create observables and make your templates reactive to changes.

Chapter 2, KnockoutJS Templates, shows how to create templates to reduce your HTML code. Templates will help you keep your designs maintainable and they can be adapted to your data.

Chapter 3, Custom Bindings and Components, shows how to extend the Knockout library to make your code more maintainable and portable.

Chapter 4, Managing KnockoutJS Events, teaches you how to communicate with isolated modules and libraries using jQuery events. Events will help you to send messages between different components or modules.

Chapter 5, Getting Data from the Server, shows how to communicate with the server from the client side using jQuery AJAX calls. You will also learn how to develop the client side without a server behind it using mock techniques.

Chapter 6, The Module Pattern – RequireJS, teaches you how to write well-formed modules using the module pattern and the AMD pattern to manage dependencies between libraries.

Chapter 7, Durandal – The KnockoutJS Framework, teaches you how the best Knockout framework works. You will learn about each part of the framework to have the capacity to make big applications with less code.

Chapter 8, Developing Web Applications with Durandal – The Cart Project, migrates the application built over the course of the book to Durandal. You will develop the same app with a few lines and will be able to add new features.

What you need for this book

The following is the list of software applications that are required at different stages:

To begin:
Twitter Bootstrap 3.2.0jQuery 2.2.1KnockoutJS 3.2.0
To manage advanced templates:
Knockout External template engine 2.0.5
A server to perform AJAX calls from the browser:
Mongoose server 5.5
To mock data and server calls:
Mockjax 1.6.1MockJSON
To validate data:
Knockout validation 2.0.0
To debug using the browser:
Chrome Knockout debugger extension
To manage file dependencies:
RequireJSRequire text pluginKnockout and helpers
The KnockoutJS framework:
Durandal 2.1.0 Starter Kit
Others:
iCheck plugin 1.0.2

Who this book is for

If you are a JavaScript developer who has been using DOM manipulation libraries such as jQuery, MooTools, or Scriptaculous and you want to go further in modern JavaScript development with a simple, lightweight, and well-documented library, then this technology and book are for you.

Learning Knockout will be perfect as your next step towards building JavaScript applications that respond to user interaction.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Refreshing the UI Automatically with KnockoutJS

If you are reading this book, it is because you have discovered that managing web user interfaces is quite complex. DOM (short for Document Object Model) manipulation using only native JavaScript is very hard. This is because each browser has its own JavaScript implementation. To solve this problem, different DOM manipulation libraries have been born in the last few years. The library most frequently used to manipulate the DOM is jQuery.

It is increasingly common to find libraries that help developers to manage more and more features on the client side. As we have said, developers have obtained the possibility to manipulate the DOM easily and therefore to manage templates and format data. Also, these libraries provide developers with easy APIs to send and receive data from the server.

However, DOM manipulation libraries don't provide us with mechanisms to synchronize input data with the models in our code. We need to write code that catches user actions and updates our models.

When a problem occurs frequently in most projects, in almost all the cases, it can surely be solved in a similar way. It was then that libraries that manage the connection between the HTML files and JavaScript code began to appear. The pattern these libraries implement was named MV* (Model-View-Whatever). The asterisk can be changed by:

Controller, MVC (for example, AngularJS)ViewModel, MVVM (for example, KnockoutJS)Presenter (MVP) (for example, ASP.NET)

The library we are going to use in this book is Knockout. It uses view-models to bind data and HTML, so it uses the MVVM pattern to manage the data binding issue.

In this chapter, you will learn the basic concepts of this library and you will begin a task to use Knockout in a real project.

KnockoutJS and the MVVM pattern

KnockoutJS is a very lightweight library (just 20 KB minified) that gives the ability to objects to become the nexus between views and models. It means that you can create rich interfaces with a clean underlying data model.

For this purpose, it uses declarative bindings to easily associate DOM elements with model data. This link between data and presentation layer (HTML) allows the DOM to refresh displayed values automatically.

Knockout set up chains of relationships between model data to transform and combine it implicitly. Knockout is also trivially extensible. It is possible to implement custom behaviors as new declarative bindings. This allows the programmer to reuse them in a just few lines of code.

The advantages of using KnockoutJS are many:

It's free and open source.It is built using pure JavaScript.It can work together with other frameworks.It has no dependencies.It supports all mainstream browsers, even ancient ones such as IE 6+, Firefox 3.5+, Chrome, Opera, and Safari (desktop/mobile).It is fully documented with API docs, live examples, and interactive tutorials.

Knockout's function is specific: to join views and models. It doesn't manage DOM or handle AJAX requests. For these purposes, I would recommend jQuery. Knockout gives us the freedom to develop our code the way we want.

MVVM-pattern diagram

A real-world application – koCart

In order to demonstrate how to use Knockout in a real application, we are going to build a simple shopping cart called koCart.

First of all we are going to define the user stories. We just need a few sentences to know what we want to achieve, which are as follows:

The user should be able to view the catalogWe should have the ability to search the catalogThe user can click on a button to add items to the catalogThe application will allow us to add, update, and delete items from the catalogThe user should be able to add, update, and delete items from the cartWe will allow the user to update his personal information.The application should be able to calculate the total amount in the cartThe user should be able to complete an order

Through user stories, we can see that our application has the following three parts:

The catalog, which contains and manages all the products we have in the shop.The cart, which has responsibility for calculating the price of each line and the total amount of the order.The order, where the user can update his personal information and confirm the order.

Installing components

To develop our real-world project, we need to install a few components and set up our first layout.

These are all the components you need to download:

Bootstrap: https://github.com/twbs/bootstrap/releases/download/v3.2.0/bootstrap-3.2.0-dist.zipjQuery: https://code.jquery.com/jquery-2.1.1.min.jsKnockoutJS: http://knockoutjs.com/downloads/knockout-3.2.0.js

Since we just work on the client side in the first chapters, we can mock data in the client and will not need a server side for now. So we can choose any place in our computer to start our project. I recommend you use the environment you usually employ to do your projects.

To start, we create a folder called ko-cart and then create three folders and a file inside it:

In the css folder, we will put all our css.In the js folder, we will put all our JavaScript.In the fonts folder, we will put all the font files needed by the Twitter Bootstrap framework.Create an index.html file.

Now you should set up your files the same way as shown in the following screenshot:

The initial folder structure

Then we should set the content of the index.html file. Remember to set all the links to the files we will need using the <script> and <link> tags:

<!DOCTYPE html> <html> <head> <title>KO Shopping Cart</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> </head> <body> <script type="text/javascript" src="js/vendors/jquery.min.js"> </script> <script type="text/javascript" src="js/vendors/bootstrap.min.js"> </script> <script type="text/javascript" src="js/vendors/knockout.debug.js"> </script> </body> </html>

With these lines of code, we have all we need to start our application.