Codemotion 2013 - Designing complex applications using html5 and knockoutjs

Post on 15-May-2015

3.861 views 1 download

Tags:

Transcript of Codemotion 2013 - Designing complex applications using html5 and knockoutjs

Designing complex applications using HTML5 and KnockoutJS

Fabio Franzini

fabio@fabiofranzini.com - @franzinifabio

About MeFabio franzini

Senior Consultant and Software Engineer MCT Trainer, MCPD Web Applications, MCTS SharePoint

2010/2007 Official Ignite Trainer for SharePoint 2013 & 2010 in Italy Web Stack Lover Over 9 years experience in IT as a software engineer

Blog: www.fabiofranzini.comEmail: fabio@fabiofranzini.com

fabio@fabiofranzini.com - @franzinifabio

AgendaFabio franzini

1. Introduction2. HTML53. JavaScript and Client Side Frameworks4. Server Side Tools5. Multiplatform6. Demo

fabio@fabiofranzini.com - @franzinifabio

IntroductionFabio franzini

What is the keys to create complex applications in javascript without becoming crazy?

1. Write clean code!!2. Modularization and Reuse of code!!3. Use frameworks or tools that simplify the work!!

fabio@fabiofranzini.com - @franzinifabio

Why HTML5?Fabio franzini

• Cross Browser• Cross Platform• W3C Standards• All modern browsers and mobile devices supports

HTML5• Rich set of controls and APIs

fabio@fabiofranzini.com - @franzinifabio

JavaScript is…Fabio franzini

• From Wikipedia:– A prototype-based scripting language that

is dynamic, weakly typed and has first-class functions. – A multi-paradigm language, supporting object-oriented,

imperative, and functional programming styles.

• In short, a big mess for most developers :)

fabio@fabiofranzini.com - @franzinifabio

Modularize your code using the module pattern!

Fabio franzini

• Group several related elements such as classes, singletons, methods, globally used, into a simple object.

• It fakes classes in Javascript.

• Pros– Encapsulation, it gives us an API (public and private attributes

or methods)– Avoid names conflicting with other function– Easier debugging (public functions are named)

• Cons:– Difficult to refactor

fabio@fabiofranzini.com - @franzinifabio

Module Pattern: ExampleFabio franzini fabio@fabiofranzini.com - @franzinifabio

var testModule = ( function() { var counter = 0; var privateMethod = function() { // do something…. } return { incrementCounter: function() { return counter++; }, resetCounter: function() { counter = 0; } };})();

Revealing Module PatternFabio franzini

Coined by Christian Heilmann (Mozilla Foundation) Pros

– Sintax more consistent and easy to read– Easier to refactor

fabio@fabiofranzini.com - @franzinifabio

var myRevealingModule = ( function() {var name = 'John Smith';

function updatePerson() { name = 'John Smith Updated'; } function setPerson (value) { name = value; } return { set: setPerson };}());

RequireJs for implement Module PatternFabio franzini

• RequireJs is a JavaScript file and module loader. • Using a modular script loader like RequireJS will improve

the speed and quality of your code!

fabio@fabiofranzini.com - @franzinifabio

[myPage.html]<script data-main="scripts/main" src="scripts/require-jquery.js"></script>…..[main.js]require(["jquery", "jquery.alpha", "jquery.beta"], function($) {

//the jquery.alpha.js and jquery.beta.js plugins have been loaded.

$(function() { $('body').alpha().beta();

}); });

Another PatternFabio franzini

• MV* Pattern– The MV* Pattern allows to separate the functionalities

and introduce greater flexibility to customize the presentation of items

– Provides a standard model interface to allow a wide range of data sources to be used with existing item views

– Different implementation: MVC, MVP, MVVM• Observer (Pub/Sub) Pattern

– It is a design pattern which allows an object (known as a subscriber) to watch another object (the publisher)

– Loose coupling, ability to break down our applications into smaller, general manageability

fabio@fabiofranzini.com - @franzinifabio

KnockoutJsFabio franzini

• Model: It uses the Observable property that can notify subscribers about changes and automatically detect dependencies

• View: A KnockoutJs View is simply a HTML document with declarative bindings to link it to the ViewModel

• ViewModel: The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model

fabio@fabiofranzini.com - @franzinifabio

KnockoutJs ViewModelFabio franzini fabio@fabiofranzini.com - @franzinifabio

function AppViewModel() { this.firstName = ko.observable("Bert"); this.lastName = ko.observable("Bertington");

this.fullName = ko.computed(function() { return this.firstName() + " " + this.lastName(); }, this);

this.capitalizeLastName = function() { var currentVal = this.lastName(); this.lastName(currentVal.toUpperCase()); }; }

// Activates knockout.jsko.applyBindings(new AppViewModel());

KnockoutJs ViewFabio franzini fabio@fabiofranzini.com - @franzinifabio

<p>First name: <input data-bind="value: firstName" /></p>

<p>Last name: <input data-bind="value: lastName" /></p>

<p>Full name: <strong data-bind="text: fullName"></strong></p>

<button data-bind="click: capitalizeLastName">Go caps</button>

List of other Powerfull JavaScript FXFabio franzini fabio@fabiofranzini.com - @franzinifabio

• AmplifyJs• UnderscoreJs• LinqJs• DurandalJs• BreezeJS

AmplifyJsFabio franzini fabio@fabiofranzini.com - @franzinifabio

Is a set of components designed to solve common web application problems with a simplistic API like

– amplify.request provides a clean and elegant request abstraction for all types of data, even allowing for transformation prior to consumption.

– amplify.publish/subscribe provides a clean, performant API for component to component communication.

– amplify.store takes the confusion out of HTML5 localStorage. It doesn't get simpler than using amplify.store(key, data)! It even works flawlessly on mobile devices.

UnderscoreJsFabio franzini fabio@fabiofranzini.com - @franzinifabio

Underscore is a utility library that provides a lots of functions without extending any of the built-in JavaScript objects

UnderscoreJs FunctionsCollection• Each• Map• Reduce• Find• Where• Any• Etc…

Arrays• First• Initial• Union• Etc…

Functions• Bind• BindAll• Wrap• Etc…

Objects• Keys• Values• Extend• isEqual• isEmpty• Etc…

Utility• Random• uniqueId• Escape• Etc..

Chaining• Chain• Value

linq.js - LINQ for JavaScriptFabio franzini fabio@fabiofranzini.com - @franzinifabio

• implement all .NET 4.0 linq to object methods and extra methods

• complete lazy evaluation• full IntelliSense support for VisualStudio• two versions: linq.js and jquery.linq.js (jQuery plugin)var jsonArray = [ { "user": { "id": 100, "screen_name": "d_linq" }, "text": "to objects" }, { "user": { "id": 130, "screen_name": "c_bill" }, "text": "g" }, { "user": { "id": 155, "screen_name": "b_mskk" }, "text": "kabushiki kaisha" }, { "user": { "id": 301, "screen_name": "a_xbox" }, "text": "halo reach" }];var queryResult = Enumerable.From(jsonArray) .Where(function (x) { return x.user.id < 200 }) .OrderBy(function (x) { return x.user.screen_name }) .Select(function (x) { return x.user.screen_name + ':' + x.text }) .ToArray();

DurandalJsFabio franzini fabio@fabiofranzini.com - @franzinifabio

Durandal is small JavaScript framework designed to make building Single Page Applications (SPAs) simple and elegant. We didn't try to re-invent the wheel. Durandal is built on libs you know and love like jQuery, Knockout and RequireJS. There's little to learn and building apps feels comfortable and familiar.

• Clean MV* Architecture• JS & HTML Modularity• Simple App Lifecycle• Eventing, Modals, Message Boxes, etc.• Navigation & Screen State Management• Consistent Async Programming w/ Promises• App Bundling and Optimization• Use any Backend Technology• Built on top of jQuery, Knockout & RequireJS• Integrates with other libraries such as SammyJS & Bootstrap• Make jQuery & Bootstrap widgets templatable and bindable (or build your own

widgets).

DurandalJs – DemoFabio franzini fabio@fabiofranzini.com - @franzinifabio

DEMODurandalJs

BreezeJsFabio franzini fabio@fabiofranzini.com - @franzinifabio

Breeze is a library for rich client applications written in HTML and JavaScript.It concentrates on the challenge of building and maintaining highly responsive, data-intensive applications in

which users search, add, update, and view complex data from different angles as they pursue solutions to real problems in real time.

Features include:• Rich queries using a LINQ-like query syntax• Client-side caching• Change tracking• Validation• Pluggable back-end

• Full integration with the Entity Framework.• Supports WebAPI and OData back-ends.• Works with NoSQL, non-.NET, and SOA back-ends

• Data management• Batched saves• Library and Tooling support

• Out-of-box support for Knockout, Angular, and Backbone.• TypeScript support for compile-time type checking, classes, interfaces, and inheritance.• IntelliSense support for Visual Studio 2012.• RequireJS-enabled for modular applications.• Open API that allows additional front or back-ends to be plugged in.

BreezeJsFabio franzini fabio@fabiofranzini.com - @franzinifabio

BreezeJs– DemoFabio franzini fabio@fabiofranzini.com - @franzinifabio

DEMOBreezeJs

Server Side ToolsFabio franzini fabio@fabiofranzini.com - @franzinifabio

• TypeScript• ScriptSharp

TypeScriptFabio franzini fabio@fabiofranzini.com - @franzinifabio

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

• TypeScript starts from the syntax and semantics that millions of JavaScript developers know today.

• You can use existing JavaScript code, incorporate popular JavaScript libraries, and be called from other JavaScript code.

• Compiles to clean, simple JavaScript code which runs on any browser, in Node.js, or in any other ES3-compatible environment.

TypeScript – Simple ExampleFabio franzini fabio@fabiofranzini.com - @franzinifabio

TypeScriptclass Greeter { greeting: string; constructor (message: string) {

this.greeting = message; } greet() { return "Hello, " + this.greeting; }}

var greeter = new Greeter("world");alert(greeter.greet());

JavaScriptvar Greeter = (function () { function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function () { return "Hello, " + this.greeting; }; return Greeter;})();var greeter = new Greeter("world");alert(greeter.greet());

ScriptSharpFabio franzini fabio@fabiofranzini.com - @franzinifabio

Script# is a free tool that generates JavaScript by compiling C# source code.

• The goal is to enable you to leverage the productivity of C#, the Visual Studio IDE, and .NET tools and apply them to your HTML5 development.

• The Script# compiler is a development/build-time tool that takes a pragmatic approach to generating script for use in real-world script-based applications, without introducing any unnecessary layers of abstraction.

Package AppsFabio franzini fabio@fabiofranzini.com - @franzinifabio

• Apache Cordova• AppJs

Apache Cordova (PhoneGap)Fabio franzini fabio@fabiofranzini.com - @franzinifabio

Is a platform for building native mobile applications using HTML, CSS and JavaScript• Pros

– The Power of HTML5– Build native App– Interact with Device API’s

• Conts– Performance of WebBrowser

Control on target device…

AppJsFabio franzini fabio@fabiofranzini.com - @franzinifabio

AppJS is an SDK to develop desktop applications using Node.js melded with Chromium.

You get all the following in one package:• JS, HTML5, CSS, SVG, WebGL — by Chromium• mature HTTP/HTTPS servers and client APIs — by Node.js• filesystem, DNS, cryptography, subprocesses, OS APIs — by

Node.js• sandboxed code execution environements, virtual machines — by

Node.js• tools for exposing native C++ bindings to JavaScript — by Node.js

Q&AFabio franzini fabio@fabiofranzini.com - @franzinifabio

;-)Questions & Answer time!