single page applications with angularjs 2.0

Download Single Page Applications with AngularJS 2.0

Post on 10-May-2015




0 download

Embed Size (px)


Single Page Applications (SPA) 2.0 - Push the limits of what’s possible on the web AngularJS, RequireJS , Polymer, AMD, ES6 , Gulp, Dependency Injection, JavaScript Patterns, Functional Reactive Programming, OAuth, Promises ,Generators


  • 1.Single Page Applications 2.0 Push the limits of whats possible on the web

2. New Topics Tool Chain, Code Organization Asset pipeline hooks Programmable CSS with SASS and Bourbon Transpile ES6 ES5 ES6/ES7 with Angular AMD with Angular DI 2.0 with Angular HTML5 Custom Elements Functional Reactive Programming with Angular NG- Patterns : Logging, Security, Resiliency, Cache 3. Tool Chain 4. Gulp - Task Runner The streaming build system. No more temp files. Gulp replace Grunt. Install: npm install -g generator-gulp-angular Run: yo gulp-angular [app-name] Run gulp for building and gulp watch for preview gulpfile.js 5. Gulp and its NPM packages Built-in preview server with LiveReload, file watcher CSS Pre-processing : SASS, Bourbon Mixins CSS Autoprefixing : add vendor prefixes JSHinting, CSSLinting : lint your scripts, CSS JS Transpilers: ES6 ES5 Awesome Image Optimization, WebP AMD/RequireJS Support Concatenation/Optimization, Minification, uglify Automatically wire-up dependencies installed with Bower (when gulp watch or gulp wiredep) 6. Code Organization Adopt De Facto Standards Yeomen generated project structure Rapid prototyping using scaffolding generators Modularity: Organize your files by Feature not by Type Modules are independent WebApp functionality that developers can work in parallel Isolate complexity into separate pluggable modules In an AngularJS context, modularization is organization by function instead of type. Everything that gets deployed is in the app directory. Everything outside of the app directory is for development 7. Compose Apps by assembling smaller modules 8. Organize Files : by Feature, Not by Type Common/ elements/ myElementTemplate.html MyElement.js services/ i18nService.js filters/ i18nFilter.js i18b/ en_EN.json de_DE.json Index.js orders/ elements/ tableTemplate.html TableElement.js table.css services/ OrderService.js index.js home/ controllers/ HomeController.js LoginController.js services/ UserService.js AuthenticationService.js i18b/ en_EN.json de_DE.json index.js index.js ../views/ home/ home.html orders/ order.html order.details.html 9. Scalable and Modular layout for stylesheets/ | |-- admin/ # Admin sub-project | |-- modules/ | |-- partials/ | `-- _base.scss | |-- account/ # Account sub-project | |-- modules/ | |-- partials/ | `-- _base.scss | |-- site/ # Site sub-project | |-- modules/ | |-- partials/ | `-- _base.scss | |-- vendor/ # CSS or Sass from other projects | |-- _colorpicker-1.1.scss # in Bower case, under bower_components | |-- _jquery.ui.core-1.9.1.scss | ... | |-- admin.scss # Primary stylesheets for each sub-project |-- account.scss |-- _variables.scss `-- site.scss Write leaner, programmable, and maintainable CSS with SASS & Bourbon 10. AMD with Angular Components Modules Root Module Bootstrap Config Config.js Bootstrap.js index.js Home Index.js routes.js Controllers Services Elements Account Index.js routes.js Controllers Services Elements Common Index.js routes.js Controllers Services Elements Dashboard Index.js routes.js Controllers Services Elements 11. Scripts loading with AMD 12. Testability Why do you need to write tests? Because youre not Chuck Norris. Unit Testing Karma: Spectacular Test Runner using real browsers! Jasmine: behavior-driven development framework for testing JavaScript code. Mocha: Simple, flexible JavaScript test framework. PhantomJS: Headless Testing Integration Testing Protractor: AngularJS E2E Testing Framework gulp test command transpile ES6 tests and perform all unit and integration tests User story: As a user, when I login to my app, I am taken to the dashboard page. 13. ECMAScript 6.0 You Cant Afford to Avoid ES6 Author In ES6, Transpile To ES5 As A Build-step: Gulp Workflow 14. Traceur & Polyfills Traceur and Shim/Polyfill makes it possible to use tomorrows technology now! Traceur is a compiler A polyfill is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will. ( from Remy Sharp blog) Traceur provide ES6 that are not available in any browser yet. Polyfill provide HTML5/ES6 features that are not available in some of the browsers yet. 15. ES6 Goodies Modules, Classes, Typed, Traits Generator, Promises, Proxies Closures / Fat Arrow Functions Let, Const, Private scope and Block Functions Destructuring, For-Of and Array Comprehensions Spread Operator, Rest Parameter, and Default Arguments Template Strings, string interpolation Collections : Set, Map, Weak Set/Map, Binary Data ES7 Object.observe , async/await functions 16. Promises Promises are useful when you want to represent the outcome of an action or a value that will be available at some future time. It is an easy way to avoid writing the Pyramid of Doom Function return a promise - no more callback parameter A promise represents an eventual outcome Promises can be pending, fulfilled or rejected they are only resolved once; Guaranteed to always be async. Promises can be chained. Re-tryable Promises as first-class objects then-able objects. then() method returns another promise and you can return data from the callback to the next promise in the chain. A deferred is an object representing work that is not yet done and a promise is an object representing a value that is not yet known. Promise Combinators: Promise.all([p1,p2,p3]) , Promise.race([p1,p2,p3]) , Promise.any([p1,p2,p3]) 17. Promises fix callback hell of async code 18. Promise Chaining Asynchronous Control Flow with Promises Promises are a replacement for Callbacks to help you deal with composition of multiple async operations while also making error handling simpler in some cases. 19. What's the Big Deal with Generators? "First-class coroutines, represented as objects encapsulating suspended execution contexts (i.e., function activations) Allows suspension of a function's execution until resolved - everything else outside of that execution continues. Higher-order functions Uses a yield statement instead of a return to report values. The essence of generator is controlling the suspension of code execution. Caller control execution of code in Generator function. Use Cases Infinite iterator : Good for representing infinite sequences. Generator return iterators. Non-blocking I/O : When we don't yield execution, we're blocking. Demand-driven: functions can interactively yield partial results as soon as available. Lazy Sequences: We can rewrite lazy version of Underscore.js using Generators. Since filter and map return generators, nothing happens until reduce. You can get benefits of declarative functional data manipulation without the performance and memory downsides of intermediate arrays. Run-to-completion(RTC) is a scheduling model in which each task runs until it either finishes, or explicitly yields control back to the scheduler. Flow Control: you can actually pass data back in to the generator, causing yield to either return a value or throw an exception inside the generator body. Synchronously looking Asynchronous code: Async functions are a thin sugar over generators and a spawn function which converts generators into promise objects 20. Generators Use case Scenarios This is a big deal: generators finally provide us with a pseudo-synchronous syntax that doesn't break run-to-completion semantics, doesn't require transpiling, and doesn't require callbacks. Basic Examples Control Flow Parallel Loops 21. Generators makes it possible write async code that looks like synchronous 22. ES7 async / await functions 23. AOP in JavaScript ES6 Proxies and Angular Decorators enable augmenting new behaviors to existing JS Objects and classes at runtime. Can be used along with Traceurs Annotations (ES6+) to add cross-cutting concerns by scanning annotations during application bootstrap process. Angular 2.0 Dependency Injection will adopt this approach. Retry aspect has been implemented using this technique in SPA Starter Kit. 24. Functional Programming What is FP? A style which utilizes HOFs and minimize side effects. Why FP? Parallelization , Concurrency , Lazy evaluation Function composition E.g. collection.filter { x -> x > 5}.map{ x -> x * x} Data1 => function1 => data2 => functions2 => data3 => ... The only requirement is F1s output type should match to F2s input type Solution : Curried functions , Monads No shared mutable state Pure functions dont change state Functions without side-effects (mutability) Functions are Deterministic. Data is immutable. Imperative Programming Functional Programming 25. Easy to change implementation. With FP, Internal Iteration implementation can be changed: forEach => parallel forEach 1,000,000 users? 26. Functional Reactive Programming FRP is all about effectively processing event streams without explicitly managing state. Modern code var a = 10; var b 11 Relative Programming output => 21 a := b + c ; meant a always equals b plus c, at any time Similarities with observer pattern Observer pattern commonly describes data-flows between whole objects/classes, whereas FRP could target the members of objects/classes. Observer pattern has limitations like Unpredictable order, Leaking listeners, Threading issues, Messy State, Compositionality, Accidental recursion etc., Similarities with 2-way data binding Models are updated with manual communication , in FRP they react to events 27. FRP Terminology Time-varying Values dynamic/evolving values (values "over time), a.k.a DataFlow Variables , e.g., temperature , vehicle speed, Stock symbol etc. Signals/Events Changing a value is an Event. Anything that happens multiple times and/or that might be triggered at random intervals should be implemented as Signals/Events. Event Streams are sources of events. Streams of ti


View more >