CHAPTER 5

image

HTML5, JavaScript, and Windows 8 Applications

If you are a regular .NET developer, then the first four chapters of this book already gave you a solid head start on developing Windows 8 applications using XAML and (probably) your favorite .NET language—C#—following one of the most popular design patterns, the MVVM design pattern. However, if you are a web developer and are more familiar with HTML and JavaScript, then how can you develop Windows 8 applications, also following the MVVM design pattern? As explained during the introduction of the book, the Windows runtime (Win RT) of Windows 8 offers a variety of platforms supporting developers to develop Windows 8 applications. One of the supportable platforms is HTML5 and JavaScript and, of course, supporting MVVM!

The next two chapters will lead you through a rewarding journey of developing the FinanceHub application using HTML 5 and JavaScript, where we will use Windows 8 JavaScript template and will follow the MVVM design pattern.

  • This chapter will provide you an overview of the Windows 8 applications development capabilities using HTML5 and JavaScript
  • The next and final chapter of this book will implement View, ViewModel, and Model of the FinanceHub application using HTML5 and JavaScript

Before we get into details of how Microsoft Windows Runtime (Win RT), development tools, and third-party JavaScript framework(s) support development of Windows 8 applications (including the support of MVVM design pattern) using HTML5 and JavaScript, let’s quickly get a overview of HTML5 and JavaScript.

HTML5 and JavaScript

As Tim O’Reilly defined Web 2.0—Web 2.0 is the business revolution in the computer industry caused by the move to the Internet as platform, and an attempt to understand the rules for success on that new platform (2006 -http://radar.oreilly.com/2006/12/web-20-compact-definition-tryi.html)SPI_AMP#x2014;today's web applications and services are built on the Internet treating the Internet as a Platform. To support such a revolutionary concept, the existing web development platforms, including one of the most popular and founding platforms—HTML—need some revolutionary changes that can support development of the next-generation web applications, supporting the concept of Web 2.0 and beyond.

The latest version of HTML—HTML5—has gained a wide popularity and is being rapidly adopted across the board to develop and deploy a true cross-platform, cross-browser and cross-device new generation of web applications on the Internet as a platform. With the rise of HTML5 popularity and its integration capabilities with JavaScript development platform, JavaScript is becoming a critical part of the web development platform. As a result, you will start seeing more JavaScript frameworks emerge, along with the integration capabilities of key development platforms and tools, such as integration capabilities with the Microsoft Windows 8 development platform and Microsoft Visual Studio 2012 development tool.

The following are some of the new key features that make HMTL5 such a promising web development platform:

  • Set of new semantic and document outlining tags that makes the definition of your web page more meaningful and structured
  • New form and input elements to allow managed-input entries with in-built validation
  • Introduction of the canvas element and JavaScript APIs to support vector graphics and animations
  • Introduction of the audio and video elements supporting native audio and video integration
  • Drag and drop API to develop desktop application-like features for the web applications
  • Geolocation API to develop location aware applications
  • SQL-based database API to enable local storage on client machines supporting offline web applications state
  • In-built web worker role to support background processing and the WebSocket interface to implement continuous connection between the HTML5 application and server
  • Last but not the least: support to CSS3 to develop rich and interactive web applications

image Note   Get HTML5 Mastery: Semantics, Standards and Styling, authored by Anselm Bradford and Paul Haines, by visiting Apress site at http://www.apress.com/9781430238614 . It’s also worth reviewing Beginning CSS3, by David Powers, available on Apress site at http://www.apress.com/9781430244738 .

Windows 8 Applications Using HTML5 and JavaScript

If you are a web developer and more familiar with HTML and JavaScript, your preference would be to develop Windows 8 applications using HTML and JavaScript. The Windows runtime (Win RT) of Windows 8 offers a variety of platforms, including using HTML5 and Javascript, supporting the development of Windows 8 applications.

Windows APIs for Windows 8 Store Applications

Microsoft Windows 8 provides two sets of Windows APIs to develop native Windows 8 store applications:

  • Windows Runtime (WinRT) – is a core language-agnostic platform providing a set of classes, methods, and properties (with Windows namespace) to develop applications using C#, VB .NET, JavaScript, C, and C++. For the JavaScript-based Windows 8 applications, the Windows Runtime is available as Windows global object.
  • Windows JavaScript Library (WinJS) – is a set of JavaScript APIs providing advanced JavaScript controls, DOM utilities, CSS styles, support to asynchronous programming, and helper functions (with WinJS namespace), which can optionally be used in Windows 8 applications to support more XAML-like abstracted development for Windows 8 applications using HTML5/JavaScript. The WinJS library is available only for JavaScript-based Windows 8 applications, and it's available as WinJS global object to the applications.

Windows JavaScript Library

WinJS is a library of objects structured under the WinJS namespace enabling object-oriented and advanced programming, including supporting the asynchronous communication, access to the local storage, and capability to define your own classes and namespaces for Windows 8 applications. We will be leveraging some of the key features of the WinJS in the next chapter to implement the FinanceHub Windows 8 application using HTML5/JavaScript, following the MVVM design pattern.

The following provides a high-level overview of namespaces available as part of Windows JavaScript Library:

  • WinJS namespace – is a root namespace for Windows JavaScript library and also provides the Promise object and abstraction to manage asynchronous communication and the xhr function that would wrap calls to XMLHttpRequest in a promise object.
  • WinJS.Applicationsupports application-level features such as storage, application, events management, etc.
  • WinJS.Binding – provides data and template binding, including capabilities for the declarative binding using data-win-bind attribute, which will be useful to develop applications supporting MVVM design pattern.
  • WinJS.Classprovides helper functions to define classes.
  • WinJS.Namespace – provides helper functions to define namespaces.
  • WinJS.Navigation – helps to build basic navigation.
  • WinJS.Resources – enables resources management to implement globalization and localization features.
  • WinJS.UI – provides a set of advanced user controls, such as AppBar, Menu, SemanticZoom, ListView, Flyout, etc. Please note that while you add a UI control from the WinJS.UI namespace, you will use the div tag in HTML5 and not the direct element name, and you use the data-win-control attribute to define the required control. The statement - <div data-win-control="WinJS.UI.ListView > </div> will add the WinJS ListView control.
  • WinJS.UI.Animationsupports implementation of Windows animation using custom controls.
  • WinJS.UI.Fragmentshelps to load HTML content programmatically.
  • WinJS . UI.Pages – supports definition and displaying of PageControl objects to implement navigation within your application.
  • WinJS.Utilities – provides helper functions, such as add and remove CSS classes.
  • Win JS Library Control Attributes – provides a set of attributes, such as data-win-control to specify the type of control and data-win-bind attribute to bind a property of an element to a property of data source, to configure Win JS UI controls within HTML markup.
  • Win JS Library Style Sheets – provides two default styles sheets to provide HTML5/JavaScript based application to Windows 8 theme. Use the ui-dark.css stylesheet for defining dark background and light foreground and ui-light.css stylesheet for defining light background and dark foreground.

You need to add one of the following stylesheets referent to your HTML markup to provide Windows 8 theme of your choice.

<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet">
Or

<link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet">

image Note   Visit Microsoft MSDN site at http://msdn.microsoft.com/en-us/library/br211377.aspx to get more information on the Windows API (including Windows JavaScript library) reference for Windows 8 store applications.

Best Practices in JavaScript Development

Believe it or not, JavaScript does follow an object-oriented programming language. It’s an interpreted prototype-based programming language. In JavaScript, you define object by creating a constructor function rather than defining a class.

image Note   Get more details on JavaScript object-oriented programming by visiting https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript link.

The following sections of this chapter would describe some of the best practices in JavaScript development that we will be following in our next chapter to develop HTML5/JavaScript-based Windows 8 FinanceHub application following MVVM design pattern.

Global Namespace Pollution and Prevention

If have experience in JavaScript development, then you might have heard about the global namespace pollution in JavaScript. In JavaScript, variables defined outside the function are globally available. These variables are part of the global namespace, and defining them is called global namespace pollution.  Thus, if you have defined such variable and you are using any 3rd party JavaScript library that contains any variable with the same name, it will create a conflict with that library. The solution to such problem is using namespace while defining objects and functions. The WinJS really helps here by providing the define method of the Namespace object as following:

WinJS.Namespace.define
    ("ViewModel",
    {
        //other members for the ViewModel object . . .
    });

In the next chapter you will notice that we will follow a namespace convention while developing model and view model JavaScript functions of our application.

Use of Self

Using self is a common JavaScript construct and is required whenever local functions need to refer to the main object. It is not a keyword but is a closure that will reference the current object via a variable named self.  This is useful to refer to members outside the local function because within the local functions, the variable this refers to the inner function itself, not to the outer object. So self is being used to maintain a reference to the original this even as the context is changing as demonstrated in the following example:

WinJS.Namespace.define
    ("ViewModel",
    {
        MyViewModel: WinJS.Class.define(
            function () {
                var self = this;
                self.Title = "";
  ....
  ....
 //Some local function
                this.changeTitle = function () {
                self.Title = "Hi";
  ....

Using the Strict Mode

The strict mode is a new feature of ECMAScript 5 (the latest standard for JavaScript), which enables you to make JavaScript stricter with enforcement. For example, when the strict mode is enabled, you cannot declare variables without using the var keyword.

You can declare strict mode by adding “use strict”; at the beginning of the JavaScript file, a program, or a function. The scope of a strict mode depends on its context at file level, program level, or at a function level based on where it is declared. Such declaration is known as a directive prologue. Once you will apply the strict mode, if your program does not follow the good programming practice, such as not defining variable using var keyword or declaration of the variable outside of the function, it will produce an error.

We will make the use of the strict mode while developing view models and model for the application in the next chapter.

image Note   To get more details on the strict mode and related restrictions, visit MSDN site at http://msdn.microsoft.com/en-us/library/br230269.aspx.

Module Pattern and Self-Executing Functions

Windows 8 applications written with JavaScript uses a JavaScript design pattern called the module pattern. The module pattern is a common pattern used in JavaScript applications to create private variables, objects, and methods. Anything that you create within the module is encapsulated within the module. Enclosing all of your code within a module prevents the conflicting of it from other libraries. You can create a self-executing module by enclosing the entire content of the file within braces, as shown below (in bold fonts).

(
    function () {
    . . .
  
    }
)() ;

In Windows 8 JavaScript application template, the automatically created default.js file follows this pattern. The advantage of self-executing function is that it executes automatically when the page that references the JavaScript loads.

Using Constructor Initialization

You should use constructor initialization, or in other words, try to make sure that an object doesn’t need any further initialization to be used once it has been constructed.

function () {
    "use strict";
      
    WinJS.Namespace.define("ViewModel", {
        MyViewModel: WinJS.Class.define(
            function () {
                var self = this;
                self.Title = "";
 . . .

In the above example you can initialize the value of Title as following:

var vm = new MyViewModel();
vm.Title = "Hi";

Instead, following the best practice, you should define MyViewModel like following (see bold fonts):

function () {
    "use strict";

    WinJS.Namespace.define("ViewModel", {
        MyViewModel: WinJS.Class.define(
            function ( title ) {
                var self = this;
                self.Title = title;
 . . .

And the use it like following:

var vm = new MyViewModel("Hi");

We will be using this good practice while developing the stock model in the next chapter.

The Knockout JavaScript Framework

There are a few third-party JavaScript frameworks, such as Knockout, Kendo MVVM and Knockback, which provide JavaScript library enabling of easier implementation of HTML5 and JavaScript-based applications following MVVM pattern.

In this book we will specifically leverage the Knockout JavaScript framework, which provides a JavaScript library that simplifies the implementation of dynamic JavaScript UIs by applying MVVM pattern.

  • Supports implementation of declarative bindings
  • Enables automatic UI-refresh implementation when there is a change in the state of applications data model
  • Implements dependency tracking by implicitly setting up chains of relationships between model data, to transform and combine it
  • Empowers you to generate template-based user interface, aligned with the model data

We will be leveraging the Knockout JavaScript framework while implementing Add and Remove stocks views in the next chapter.

image Note   To get more details and download Knockout JavaScript framework, visit http://knockoutjs.com/.

Summary

This was an introductory chapter providing you a quick overview of HTML5, JavaScript, and best practices to develop JavaScript program. We also looked at Microsoft Windows 8development platform and development tools support to develop Windows 8 store applications using HTML5 and JavaScript. Microsoft Windows 8 Runtime not only supports the development of Windows 8 applications using HTML5 and JavaScript in a language-agnostic environment using Microsoft Visual Studio 2012 but also provides a dedicated JavaScript library (WinJS) to develop advanced JavaScript-based Windows 8 store applications.

The next and final chapter of this book will create an HTML5 and JavaScript-based Windows 8 FinanceHub application using one of the Windows 8 JavaScript templates available in Visual Studio 2012 and then implementing View, ViewModel, and Models of the FinanceHub applications, following MVVM design pattern. During this implementation we will also leverage the Knockout JavaScript third-party framework.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.149.180