Getting Started with Knockout.js for .NET Developers - Andrey Ankshin - E-Book

Getting Started with Knockout.js for .NET Developers E-Book

Andrey Ankshin

0,0
23,99 €

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

Mehr erfahren.
Beschreibung

This book is intended for .NET developers who want to use the MVVM design pattern to create powerful client-side JavaScript linked to server-side C# logic. Basic experience with ASP.NET, Razor, and creating web applications is needed.

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

EPUB
MOBI

Seitenzahl: 175

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

Getting Started with Knockout.js for .NET Developers
Credits
About the Author
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. Introduction to Knockout.js
Knockout.js overview
What is Knockout.js?
The best features
MVVM design pattern
Installing Knockout.js
Method 1 – official site
Method 2 – NuGet
Method 3 – CDNs
Method 4 – GitHub
Knockout.js fundamentals
Creating a View
Adding a ViewModel
Adding a data binding
Adding an observable
Subscribing to observables
Updating View in a forced way
Delaying and suppressing change notifications
Adding dynamic behavior
A binding diversity
Single and multiple bindings
Value representation
White spaces
Skipping the value
Useful links
Summary
2. Creating a Simple Knockout.js Application
Creating the Model, View, and ViewModel
Text and appearance bindings
The text binding
The html binding
The css binding
The style binding
The attr binding
The visible binding
Form fields bindings
The value binding
The click binding
The submit binding
The event binding
The checked binding
The enable and disable binding
The options binding
The selectedOptions binding
Control flow bindings
The foreach binding
The if and ifnot bindings
The with binding
Computed observables
Using a computed observable
Computed observable features
Observable arrays
Using an observable array
Adding to an observable array
Removing from an observable array
Manipulating an observable array
Summary
3. Integrating Knockout.js in ASP.NET MVC Applications
Creating an application without Knockout.js
Creating a new project
Adding models
Adding views
Adding the Controller
Running the application
Creating an application with Knockout.js
Motivation
Creating a new project
Adding models
Adding views
Adding the controller
Running the application
Summary
4. Creating a Web Application with Knockout MVC
Getting started with Knockout MVC
Motivation
When you should use Knockout MVC
Installation
Useful links
Working with the Hello World example in Knockout MVC
Adding the model
Adding the controller
Adding the view
Running the application
Under the hood
Developing a Knockout MVC application
Adding the model
Adding the controller
Adding the view
Running the application
Under the hood
Summary
5. Advanced Features of Knockout.js
Loading and saving JSON data
Converting data to JSON
Converting JSON to data
Introducing Knockout mapping
A manual mapping example
An automatic mapping example
Mapping in Knockout MVC
Mapping unique values
Partial mapping – create
Partial mapping – update
Partial mapping – ignore
Multiple mappings
Advanced mapping
Binding context
Custom bindings
Registering a new binding
Binding callbacks' parameters
A custom binding example 1 – slideVisible
A custom binding example 2 – hasFocus
Extending observables
Creating an extender
An extending observables example 1 – numeric
An extending observables example 2 – required
Custom functions
An example with array filtering
Different templating approaches
A simple named template
Template in the foreach mode
The foreach template with alias
Choosing a template dynamically
Summary
6. Advanced Features of Knockout MVC
Regions
The foreach region
The with region
The if region
Complex bindings
Sending parameters to the server
Inner computed properties
Multiple view models
Lazy loading
Writing user scripts
Summary
A. A Brief on Knockout MVC References and Features
Working with KnockoutContext
Basic data binding
Form objects
Nested contexts
Sending requests to the server
Adding user-defined scripts
Forming a model and using computed properties
Special addressing forms
Summary
Index

Getting Started with Knockout.js for .NET Developers

Getting Started with Knockout.js for .NET Developers

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: May 2015

Production reference: 1200515

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78398-400-8

www.packtpub.com

Credits

Author

Andrey Akinshin

Reviewers

Dmitry Pavlov

Tim Stuyckens

Commissioning Editor

Taron Pereira

Acquisition Editors

Owen Roberts

Greg Wild

Content Development Editors

Akshay Nair

Rohit Kumar Singh

Technical Editor

Taabish Khan

Copy Editor

Adithi Shetty

Project Coordinator

Mary Alex

Proofreaders

Safis Editing

Paul Hindle

Indexer

Priya Sane

Production Coordinator

Nitesh Thakur

Cover Work

Nitesh Thakur

About the Author

Andrey Akinshin has a PhD in computer science, and he received a Microsoft MVP award in 2015. He works as a lead .NET Developer at Perpetuum Software and as a postdoctoral research fellow at the Weizmann Institute of Science. He is also the author and main contributor of the Knockout MVC library and has a wealth of experience in Knockout.js. He has experience in various IT areas, from competitive programming (silver medal at ACM ICPC 2009) to teaching (senior lecturer and the school coach of competitive programming and mathematics teams).

You can find more information about Andrey on his home page, http://aakinshin.net.

About the Reviewers

Dmitry Pavlov is a 34-year-old IT guy from Saint Petersburg, Russia. He holds two degrees. His first alma mater was Saint Petersburg State University, where he graduated from the geological department with a master's degree. Then, he got interested in programming and decided to study computer science at Saint Petersburg Polytechnic State University, where he also got a master's degree. For more than 10 years, he has been involved in .NET programming at several software companies. He has held the Microsoft MVP (Visual C#) award since 2008. He has a keen interest in IT business, software development, technologies, and IT start-ups. For the last few years, he has been working as a freelance contractor and consultant, traveling with his family all over the world and enjoying his remote work.

Currently, he works as a remote ASP.NET MVC / .NET / C# developer for Toptal clients. In addition, he is a technical recruiter at Toptal (a global network of top freelance software developers).

Tim Stuyckens is a passionate web developer with several years of experience in JavaScript-heavy applications. He has been working with Knockout.js from the moment it became publicly available and since then, he has helped large .NET teams create dynamic websites. He currently works as a consultant for HR software, which is used by more than 100,000 users.

His most known open source work is the Chrome Knockout.js context debugger extension, which has more than 25,000 weekly users.

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

Development of a big web application is a hard task. Because of this, people try to use different useful and flexible approaches to build the architecture of their applications. One such approach is Knockout.js. It is a JavaScript library that provides you with a sophisticated way to communicate between your UI and the underlying data model to create rich web user interfaces based on the Model-View-ViewModel (MVVM) pattern. Knockout.js provides a simple two-way data binding mechanism between your data model and UI, which means that any change to your data model is automatically reflected in the UI and vice versa. Instead of using pure Knockout.js, you can use Knockout MVC. It is a library for ASP.NET MVC, which is a wrapper for Knockout.js that helps to move the entire business logic to the server side; the complete JavaScript code necessary on the client side will be generated.

This book will provide you with the skills you need to successfully create a Knockout.js-based application of varying complexity, from a simple Knockout.js web page in pure JavaScript to a complex ASP.NET web application. You will learn how you can use the MVVM design pattern, including the dependency tracking system and observable properties for creation of powerful sites with a clear separation of model, logic, and view layers.

What this book covers

Chapter 1, Introduction to Knockout.js, teaches basic Knockout.js concepts (overview), such as MVVM design pattern (including the creation of Model, ViewModel, and View), binding, observables, and subscribe machinery. Also, we'll consider an installation process for the library.

Chapter 2, Creating a Simple Knockout.js Application, covers how to use advanced Knockout.js features, such as working with observables arrays, special bindings, and computed observables.

Chapter 3, Integrating Knockout.js in ASP.NET MVC Applications, uses our Knockout.js experience to create a simple ASP.NET MVC application. We'll create a simple application in pure Knockout.js + ASP.NET MVC without external libraries. We'll cover how to create a Model in C# and connect it with the MVVM structure in JavaScript.

Chapter 4, Creating a Web Application with Knockout MVC, discusses how to move the entire business logic to the server side; the complete JavaScript code necessary on the client side will be generated automatically based on the described C# (or VB.NET) model.

Chapter 5, Advanced Features of Knockout.js, covers how to use advanced Knockout MVC features. The basic set will be enough for a very simple application. Any real application needs special concepts, such as regions, complex bindings, combined contexts, and so on. You may need to transfer some parameters to the server, write your own user scripts, or perform lazy loading of your data in the case of big data.

Chapter 6, Advanced Features of Knockout MVC, discusses how to use advanced Knockout MVC features. The basic set will be enough for a very simple application. Any real application needs special concepts, such as regions, complex bindings, combined contexts, and so on. You may need to transfer some parameters to the server, write your own user scripts, or make lazy loading of your data in the big data case.

Appendix, A Brief on Knockout MVC References and Features, lists some references and features that will be useful to readers.

What you need for this book

For this book, you need to have the following software set up:

Web browser: Internet Explorer, Mozilla Firefox, or Google ChromeText editor: Notepad++ or Sublime TextC# IDE with ASP.NET support: Visual Studio C# Express or Visual Studio Community

You can work on Windows, Mac OS, or Linux.

Who this book is for

This book is intended for .NET developers who want to use the MVVM design pattern to create a powerful client-side JavaScript linked to server-side C# logic. Basic experience with ASP.NET, Razor, and creating web applications is needed. Also, elementary knowledge of C# or JavaScript is expected.

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 Errata Submission Form 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. Introduction to Knockout.js

Knockout.js is a popular JavaScript library that allows easy creation of powerful web applications based on the Model-View-ViewModel (MVVM) design pattern.

In this chapter, we will cover the following topics:

Knockout.js overviewInstalling Knockout.jsKnockout.js fundamentals

Knockout.js overview

In this section, we will take a look at Knockout.js, including a brief introduction and the best features. If you already have some experience with the library, then you can skip this chapter and go to Chapter 2, Creating a Simple Knockout.js Application, to read about the advanced features.

What is Knockout.js?

Knockout.js is an open source standalone JavaScript library developed by Steve Sanderson in 2010. The main concept of the library is implementation of the Model-View-ViewModel design pattern for web applications on the client side. The library has powerful tools to make your JavaScript code and HTML/CSS markup easier and more readable with the help of so-called observables objects and declarative bindings.

Thus Knockout.js can help you create rich HTML pages with a clean underlying data model and dynamically self-updatable UI even for very big applications with complex logic and interfaces.

The best features

Knockout.js has a lot of features that distinguish it from other similar JavaScript frameworks. There are different solutions to create the common logic of your application and interaction between data and user interface. When you select the main library to build an application, you should understand its benefits.

The following are the best features of Knockout.js:

Nice dependency tracking based on MVVM: Once data is changed, HTML will be automatically updated. You shouldn't think about updating DOM when writing logic code. We will discuss the MVVM pattern in more detail later.Two-way declarative bindings: This is a very simple way to link DOM elements to your data model, as shown in the following line of code:
<button data-bind="enable: items().count < 7">Add</button><input data-bind="value: username" />
Simple and extensible: You can write your own type of declarative bindings for any purpose. Each new binding is defined by two simple functions for the init and update events. For example, you can define a binding for the duration of a slide animation, as follows:
<div data-bind="slideDuration: 600">Content</div>
Absence of dependency: You don't need any third-party libraries. However, you may need the jQuery library for some advanced features support or performance issues, but most applications already use this library.Pure JavaScript: Knockout.js doesn't use any JavaScript superstructure, such as TypeScript or CoffeeScript. The source code of the library is represented by the pure and readable JavaScript code; it works with any server- or client-side technology.Compatibility with mainstream browsers: Knockout.js supports Mozilla Firefox 2+, Google Chrome 5+, Opera 10+, Safari, and even Internet Explorer 6+. It also works excellently on mobile (phone and tablet) devices.Small size: The size of Knockout.js is around 46 KB after gzipping for version 3.1.0. The debug versions (without compression) have a size of around 214 KB but you don't need it in the production case.Templating: The powerful template system will allow you to create reusable HTML chunks, which you can use for parts of a web page. It also has a nice syntax, as shown in the following code:
<script type="text/html" id="person-template"> <h3 data-bind="text: name"></h3> <p>Credits: <span data-bind="text: credits"></span></p> </script>

MVVM design pattern

The Model-View-ViewModel is a design pattern with a clear separation of the user interface from business logic. The main components of MVVM are as follows:

Model: This represents the state and operations of your business objects and is independent of UI. When using Knockout.js, you will usually make Ajax calls to some server-side code to read and write this stored model data.View: This is a visible UI representing your business objects.ViewModel: This is an intermediary between the View and Model, and is responsible for handling the UI logic.

You can see the scheme of MVVM in the following diagram:

The MVVM pattern looks like the classic Model-View-Controller (MVC) pattern. The Model is also your stored data, the View is also a graphical representation of your data for the user, but instead of a controller, MVVM uses a ViewModel for interaction between the Model and View. The MVVM has a number of advantages over the MVC, such as the following:

Low coupling: It's a property of the MVVM by design, because of which we use a clearer separation between the data, interface, and behavior. MVVM has a clearer separation between the data, interface, and behavior for most application architectures.Testable: Low coupling makes the application more comfortable for unit-testing; now you can separately test each layer of your application. Testing UI logic by testing only ViewModel is an easier way than testing a complete HTML page.Сode extensibility: Separation by layers makes it easier to extend each specific part of the code without affecting the others.Two-way data-binding: This avoids having to write a lot of boilerplate code.

Let's consider MVVM in examples. In parentheses, you can see the representation format of each layer, but note that these are just examples; different applications use different formats:

Knockout.js: This is the target case for this book. Most often, a Knockout.js application will use the following schemes:
Model