32,39 €
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:
Seitenzahl: 223
Veröffentlichungsjahr: 2015
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
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
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.
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.
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.
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.
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.
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.
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.
The following is the list of software applications that are required at different stages:
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.
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.
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.
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.
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 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.
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.
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:
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 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:
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
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:
Through user stories, we can see that our application has the following three parts:
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:
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:
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:
With these lines of code, we have all we need to start our application.