jscript hotspots – angularjs,angular2, reactjs, - john...
TRANSCRIPT
![Page 1: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/1.jpg)
Jscript Hotspots – AngularJS,Angular2,
ReactJS, Node.js & more
כץויריבשיבקיאיר
Agenda
• Introduction– Web Development Trends
– Modern Web App Architecture
– Tools & Frameworks Overview
• Deep Dive into selected JavaScript Frameworks– Knockout
– Ember
– AngularJS
– Angular 2
– ReactJS
– NodeJS
![Page 2: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/2.jpg)
HTML enhanced for web apps!
Yair Shivek (Siwek) [email protected]
The Challenge with Web Apps (SPA)▪ DOM Manipulation
▪ Routing
▪ Templates & Data Binding
▪ Ajax
▪ Modules
▪ History
▪ Caching
▪ Validations
▪ Testing
▪ Maintenance
▪ Memory Leaks
![Page 4: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/4.jpg)
AngularJS DirectivesOperation
▪ ng-change▪ ng-checked▪ ng-click▪ ng-href▪ ng-selected
Binding
▪ ng-bind▪ ng-model▪ ng-init▪ ng-src▪ ng-style
Template
▪ ng-csp▪ ng-disabled▪ ng-hide | show▪ ng-mouse ▪ ng-repeat▪ ng-switch▪ ng-transclude▪ ng-view
Application
▪ ng-app▪ ng-controller
Forms
▪ ng-pattern▪ ng-minlength▪ ng-maxlength▪ ng-required▪ ng-list▪ ng-true-value▪ ng-false-value▪ ng-option▪ ng-submit
• Element-Type Directive• Class-Type Directive• Custom Directive
Angular Filters
▪ number
▪ currency
▪ date
▪ lowercase
▪ uppercase
▪ filter
▪ json
▪ limitTo
▪ orderBy
![Page 5: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/5.jpg)
AngularJS Architecture
Controller, Scope & View
![Page 6: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/6.jpg)
The AngularJS Scope $watches
Scope Type
AngularJS Scope
Properties:▪ $id
Events:▪ $destroy
Lifecycle Methods▪ $destroy()▪ $new(isolate)
Communication Methods:▪ $broadcast(name, args)▪ $emit(name, args)▪ $on(name, listener)▪ $watch(…)
Runtime Methods:▪ $apply(exp)▪ $digest()▪ $eval(exp)▪ $evalAsync(exp)
![Page 7: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/7.jpg)
Modules and the Injector
Module API▪ config(configFn)
▪ constant(name, object)
▪ controller(name, constructor)
▪ directive(name, directiveFactory)
▪ factory(name, providerFunction)
▪ filter(name, filterFactory)
▪ provider(name, providerType)
▪ run(initializationFn)
▪ service(name, constructor)
▪ value(name, object)
![Page 8: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/8.jpg)
Just before demo - Structure !!!
Let’s start with a right foot…
We will use YEOMAN to guide us into a consistent project and code structure. It is important for us and for those coming after us.
Application structureControllersDirectiveFilterRouteServiceView
![Page 9: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/9.jpg)
Forms in AngularJS
Agenda
▪ Overview
Data-binding
CSS update
Value formatting and parsing
Validation
![Page 10: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/10.jpg)
Forms in AngularJS<form name="form" class="css-form" novalidate>
disable browser's native form validation
Name: <input type="text" ng-model="name"/>E-mail:<input type="email" ng-model="email" required/>Gender:<input type="radio" ng-model="gender" value="male"/> male<input type="radio" ng-model="gender" value="female"/> female
Data Binding
</form>
<button ng-click="reset()"ng-disabled="isUnchanged(user)">RESET
</button><button ng-click="update(user)"
ng-disabled="form.$invalid || isUnchanged(user)">SAVE
</button>
Operations
validation
<style type="text/css">.css-form input.ng-invalid.ng-dirty {background-color: #FA787E;}.css-form input.ng-valid.ng-dirty {background-color: #78FA89;}
</style>
Form Validations
![Page 11: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/11.jpg)
Types
➢ Text➢ Checkbox➢ File➢ Password➢ Email➢ URL➢ Number➢ Range➢ Date
Form Validation
Validations
➢ novalidate➢ Required➢ Pattern➢ Minlength➢ Maxlength➢ Min➢ Max➢ Change
Status
➢ $error➢ $pristine➢ $dirty➢ $valid➢ $invalid
CSS
➢ ng-valid➢ ng-invalid➢ ng-pristine➢ ng-dirty
Submit
➢ ng-click➢ ng-submit
Validation Types
<input type="checkbox"ng-model="{string}"[name="{string}"][ng-true-value="{string}"][ng-false-value="{string}"][ng-change="{string}"]>
<input type="email"ng-model="{string}"[name="{string}"][required][ng-required="{string}"][ng-minlength="{number}"][ng-maxlength="{number}"][ng-pattern="{string}"]>
<input type="number"ng-model="{string}"[name="{string}"][min="{string}"][max="{string}"][required][ng-required="{string}"][ng-minlength="{number}"][ng-maxlength="{number}"][ng-pattern="{string}"][ng-change="{string}"]> <input type="radio"
ng-model="{string}"value="{string}"[name="{string}"][ng-change="{string}"]>
<input type="text" | type="URL" ng-model="{string}"[name="{string}"][required][ng-required="{string}"][ng-minlength="{number}"][ng-maxlength="{number}"][ng-pattern="{string}"][ng-change="{string}"]>
![Page 12: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/12.jpg)
FormControllerKeeps track of all its controls and nested forms as well as state of them.
FormController
➢ $error➢ $pristine➢ $dirty➢ $valid➢ $invalid
NgModelController
<buttonng-click="update(user)"ng-disabled="form.$invalid || isUnchanged(user)">SAVE
</button>
<spanng-show="form.uEmail.$dirty && form.uEmail.$invalid">Invalid:<span ng-show="form.uEmail.$error.required">
Tell us your email.</span><span ng-show="form.uEmail.$error.email">
This is not a valid email.</span></span>
FormController Properties Sample
NgModelController Properties Sample
NgModelController
Provides API for the ng-model directive.
The controller contains services for:
➢ Data-binding
➢ Validation
➢ CSS update
➢ Value formatting and parsing
![Page 13: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/13.jpg)
NgModelController
View(Form)
Model
NgModelController
➢ $render()➢ $setValidity()➢ $setViewValue()
➢ $viewValue➢ $modelValue
➢ $parsers➢ $formatters
➢ $error➢ $pristine➢ $dirty➢ $valid➢ $invalid
Custom Validation Flow▪ The validation can occur in two
places:
▪ Model → View update.
▪ View → Model update.
View Model$formatters$setValidity
$parsers $setValidity
![Page 14: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/14.jpg)
Custom Validation ( View to Model )
app.directive('smartFloat', function () {return {
require: 'ngModel',link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift( function (viewValue) {if ( FLOAT_REGEXP.test(viewValue) ) {
// it is validctrl.$setValidity('float', true);return parseFloat(viewValue.replace(',', '.'));
} else {// it is invalid, return undefined (no model update)ctrl.$setValidity('float', false);return undefined;
}});
}};
});
<div>Length (float):<input type="text" ng-model="length" name="length" smart-float />{{length}}<br /><span ng-show="form.length.$error.float">This is not a valid float number!</span>
</div> Custom Directive Validation
Custom Validation ( Model to View )
app.directive('contenteditable', function() {return {
require: 'ngModel',link: function(scope, elm, attrs, ctrl) {
// view -> modelelm.bind('blur', function() {
scope.$apply(function() {ctrl.$setViewValue(elm.html());
});});
// model -> viewctrl.$render = function() {
elm.html(ctrl.$modelValue);};
// load init value from DOMctrl.$setViewValue(elm.html());
}};
});
<div ng-model="content" title="Click to edit" contentEditable="true" >Some</div><pre>model = {{content}}</pre>
Custom Directive Validation
![Page 15: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/15.jpg)
Agenda
▪ Service Overview
Angular Services
Custom Services
Angular ServicesAngular services are singletons that carry out specific tasks.
All services in Angular are instantiated lazily.
There are three functions for creating generic services, with different levels of complexity and ability:➢ Service
➢ Factory
➢ Provider
![Page 16: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/16.jpg)
$http ServiceThe AngularJS XHR API follows what is commonly known as the Promise interface.
➢ Use the then method to register callbacks, and these callbacks will receive a single argument – an object representing the response. $http({ method: 'GET', url: '/someUrl' }).success(function (data, status, headers, config) {
// this callback will be called asynchronously// when the response is available
}).error(function (data, status, headers, config) {
// called asynchronously if an error occurs// or server returns response with an error status.
});
$http Shortcut methodsComplete list of shortcut methods:
➢ $http.get
➢ $http.head
➢ $http.post
➢ $http.put
➢ $http.delete
➢ $http.jsonp
$http.get('/someUrl').success( successCallback );$http.post('/someUrl', data).success( successCallback );
![Page 17: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/17.jpg)
Setting HTTP HeadersThe $http service will automatically add certain HTTP headers to all requests.
These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object.angular.module('MyApp', []).config(function ($httpProvider) {
// Remove the default AngularJS X-Request-With headerdelete $httpProvider.defaults.headers.common['X-Requested-With'];// Set DO NOT TRACK for all Get requests$httpProvider.defaults.headers.get['DNT'] = '1';
});
$http.get('api/user', {// Set the Authorization header. In an actual app, you would // get the auth token from a service.headers: {'Authorization': 'Basic Qzsda231231'},params: {id: 5}
}).success(function() { // Handle success });
Transforming Requests & ResponsesAngularJS applies some basic transformations on all requests and responses made through its $http service.➢ Request transformations:
➢ If the data property of the request configuration object contains an object, serialize it into JSON format.
➢ Response transformations:➢ If XSRF prefix is detected, strip it ➢ If JSON response is detected, deserialize it using a JSON parser.
var module = angular.module('myApp');
module.config(function ($httpProvider) {$httpProvider.defaults.transformRequest = function (data) {
// We are using jQuery’s param method to convert our// JSON data into the string formreturn $.param(data);
};});
![Page 18: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/18.jpg)
$http CachingTo enable caching, set the configuration property cache to true.
When the cache is enabled, $http stores the response from the server in local cache.
➢ Next time the response is served from the cache without sending a request to the server.
$http.get('http://server/myapi', {cache: true
}).success(function() { // Handle success });
Response interceptorsThe interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.responseInterceptors array.// register the interceptor as a service$provide.factory('myHttpInterceptor', function ($q, dependency1, dependency2) {
return function (promise) {return promise.then(function (response) { // do something on success return response;
}, function (response) {
// do something on errorif (canRecover(response)) { return responseOrNewPromise }return $q.reject(response);
});}
});$httpProvider.responseInterceptors.push('myHttpInterceptor');
// register the interceptor via an anonymous factory$httpProvider.responseInterceptors.push(function ($q, dependency1, dependency2) {
return function (promise) { // same as above }});
![Page 19: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/19.jpg)
$resource Service in ngResource
A factory which creates a resource object that lets you interact with RESTful server-side data sources.
Installation:➢ angular-resource.js
➢ angular.module('app', ['ngResource']);
$resource(url[, paramDefaults][, actions]);
$resource Parametersurl - $resource('http://example.com\\:8080/api')
paramDefaults(optional) – {Object=}➢ Each key value in the parameter object is first bound to url template
if present and then any excess keys are appended to the url search query after the ?.
➢ Given a template /path/:verb and parameter {verb:'greet', salutation:'Hello'} results in URL /path/greet ? salutation=Hello.
actions(optional) – {Object.<Object>=}➢ Hash with declaration of custom action that should extend the default
set of resource actions.{ action1: {method:?, params:?, isArray:?}, action2: {method:?, params:?, isArray:?}, ...}
➢ action – {string} – The name of action.
➢ Method – GET,POST,DELETE & JSONP
➢ Params - Optional set of pre-bound parameters for this action.
➢ isArray - bool
![Page 20: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/20.jpg)
$resource Returns Values{Object} – A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:
{ 'get': {method:'GET'},'save': {method:'POST'},'query': {method:'GET', isArray:true},'remove': {method:'DELETE'},'delete': {method:'DELETE'} };
var User = $resource('/user/:userId', { userId: '@id' });var user = User.get({ userId: 123 }, function () {
user.abc = true;user.$save();
});
$q ServiceA promise/deferred implementation inspired by Kris Kowal's Q.
“Interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.”
step1(function (val1) {step2(value1, function (val2) {step3(value2, function (val3) {step4(value3, function (val4) {// Do something with val4
});});
});});
Q.fcall(step1).then(step2).then(step3).then(step4).then(function (val4) {// Do something with val4
}, function (error) {// Handle any error from step1 // through step4
}).done();
No Promise Promise
![Page 21: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/21.jpg)
Deferred API
The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signalingthe successful or unsuccessful completion of the task.
A new instance of deferred is constructed by calling $q.defer().
resolve(value)
reject(reson)
The Promise API
▪ A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.
▪ The promise object allow for interested parties to get access to the result of the deferred task when it completes.➢ then(successCallback, errorCallback)
![Page 22: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/22.jpg)
Write Async Methodfunction asyncGreet(name) {
var deferred = $q.defer();setTimeout(function () {
scope.$apply(function () {if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');} else {deferred.reject('Greeting'+name+'is not
allowed.');}
});}, 1000);return deferred.promise;
}asyncGreet('Robin Hood').then( function (greeting) {
alert('Success: ' + greeting);}, function (reason) {
alert('Failed: ' + reason);});
Registering Servicesyou can register the service with the module either via the Module api or by using the $provide service in the module configuration function.
var myModule = angular.module('myModule', []);myModule.factory('serviceId', function () {
var shinyNewServiceInstance;//factory function body that constructs shinyNewServiceInstancereturn shinyNewServiceInstance;
});
angular.module('myModule', [], function ($provide) {$provide.factory('serviceId', function () {
var shinyNewServiceInstance;//factory function body that constructs shinyNewServiceInstancereturn shinyNewServiceInstance;
});});
Option I
Option II
![Page 23: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/23.jpg)
$provideThe providers are the factories for the instance.
The providers share the same name as the instance they create with Provider suffixed to them.
A provider is an object with a $get() method.
➢ The injector calls the $get method to create a new instance of a service.
$provide Methodsservice(name, constructor)➢ you will be provided the actual function
reference passed to module.service.
factory(name, $getFn)➢ you will be provided the value that is returned by
invoking the function reference passed to module.factory.
provider(name, provider)➢ you will be provided the value that is returned by
invoking the $get method of the function reference passed to module.provider.
![Page 24: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/24.jpg)
Angular $provide (Custom Service)
Dependency Injection ($inject)Each Angular application has an injector.
The injector is a service locator that is responsible for construction and lookup of dependencies.
![Page 25: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/25.jpg)
Dependency Injection ($inject)<div ng-controller="MyController"><button ng-click="sayHello()">Hello</button>
</div>
function MyController($scope, greeter) {$scope.sayHello = function () {
greeter.greet('Hello World');};
}
// The 'ng-controller' directive does this behind the scenesinjector.instantiate(MyController);
Dependency AnnotationThe injector needs to know what services to inject into the function.
function MyController($scope, greeter) {...
}
Option I
var MyController = function(renamed$scope, renamedGreeter) {...
}MyController.$inject = ['$scope', 'greeter'];
Option II
someModule.factory('greeter', ['$window', function(renamed$window) {...
}]);
Option III
![Page 26: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/26.jpg)
Angular $provide (Custom Service)
Appendix
![Page 27: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/27.jpg)
Insolate Scope with Data Binding<my-directiveinterpolated ="{{parentProp1}}"twowayBinding ="parentProp2"isolated-exp-foo ="updateFoo(newFoo)"
>...</my-directive>scope: {
interpolatedProp: '@interpolated', // One-way BindingtwowayBindingProp: '=twowayBinding', // Two-way BindingisolatedExpFooMeto: '&isolatedExpFoo' // Function Binding
}
// Option IIscope: {
interpolated: '@' ,twowayBinding: '=' ,isolatedExpFoo: '&'
}
Code
Insolate Scope
![Page 28: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/28.jpg)
Transclude▪ Compile the content of the element and
make it available to the directive.<div ng-controller="Ctrl3">
Title: <input ng-model="title"> <br>Text: <textarea ng-model="text"></textarea><div class="zippy" zippy-title="Details: {{title}}">{{text}}</div>
</div>angular.module('zippyModule', [])
.directive('zippy', function () {return {
restrict: 'C',replace: true,transclude: true,scope: { title: '@zippyTitle' },template: '<div>' +
'<div class="title">{{title}}</div>' +'<div class="body" ng-transclude></div>' +'</div>',
link: function(scope, element, attrs) {...}};
});
Code
Transclude Options▪ transclude: true
➢ The directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope.
➢ The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope.
➢ When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcludedscope.
Code
![Page 29: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/29.jpg)
Custom Filter
angular.module("demo", []).filter('reverse', function () {
return function(input, uppercase) {var out = "";for (var i = 0; i < input.length; i++) {
out = input.charAt(i) + out;}
// conditional based on optional argumentif (uppercase) {
out = out.toUpperCase();}return out;
};});
Reverse: {{ greeting | reverse }}<br>Reverse + uppercase: {{ greeting | reverse : true }}<br>
![Page 30: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/30.jpg)
Angular 2
Yair Shivek
Agenda 1 of 5
Module 1 - Introduction to Angular 2
• Single Page Applications (SPA)
• The need for javascript framework
• AngularJS vs. Angular 2 vs. React
• Setting up the environment
• “Hello Angular 2” - your first app.
Module 2 - Type Script
• Angular 2 is built on Type Script
• JavaScript, ECMAScript5 , ECMAScript 6 and Type Script
• Types
• Classess
• Inheritance
• Generics Modules
• Raytracer
• Tools
![Page 31: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/31.jpg)
Agenda 2 of 5
Module 3 - Angular 2 behind the hood
• Angular 2 architecture
• How angular 2 works
• The application
• The model
• The components
• The component decorator
• Putting it all together
Introduction to Angular 2
• Single Page Applications (SPA)
• The need for a javascript framework
• AngularJS vs. Angular 2 vs. React
• Setting up the environment
• “Hello Angular 2” - your first app.
![Page 32: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/32.jpg)
Single Page Applications (SPA)
• The evolution of web technologies
• Round Trips to the server and User Experience UX
• Using XHR / Ajax to solve local slow pages.
• Where is my code?
• Maintenance Maintenance Maintenance .
• What is Single Page Application (SPA)
The need for a javascript framework
• Javascript is the language
• What is your design pattern?
• Are you going to use MVC MVVM or MVA?
• Maintenance Maintenance Maintenance !!!
• The need for a framework
• The quality of the Open Source code
• Who stand behind that open source code?
• Implementing best practices.
• Suppuration of concerns
![Page 33: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/33.jpg)
The need for a javascript framework - what do we
need?• DOM Manipulation
• Routing
• Templates & Data Binding
• Ajax
• History, Caching, Forms, Validations ...
• Performance
• Responsiveness and Mobile Orientation
• Modularity
• e2e testing integration
• Low maintenance
• Large community
AngularJS vs. Angular 2 vs. React
• Many libraries and frameworks out there.
• Let “Google Trends” tell the story
• Check usability at npm and github
• What are the major difference between the three
leaders
• The Impact of the Angular 2 release
• Updating Angular 1.5 to Angular 2
![Page 34: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/34.jpg)
Angular 2 - Setting up the environment
• Install Node Package Management (npm)– https://nodejs.org/en/
• Install Typescript– npm install -g typescript
• Install Angular CLI
“Hello Angular 2” - your first app.
DEMO
![Page 35: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/35.jpg)
Typescript
● Angular 2 is built on Type Script
● JavaScript, ECMAScript5 , ECMAScript 6 and Type Script
● Types
● Classess
● Interfaces
● Inheritance
● Generics Modules
● Raytracer
● Tools
Angular 2 is built on Type Script
• Classes
• Modules
• Decoratos
![Page 36: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/36.jpg)
JavaScript, ECMAScript5 , ECMAScript 6 and
Type Script●How typescript helps us with the current
ECMAScript5 standart
●What about tomorrow's ECMAScript6 ?
●What about 7 & 8 & next …?
●Check the typescript playground
○ https://www.typescriptlang.org/play/index.html
Typescript classes
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
![Page 37: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/37.jpg)
Typescript Interfaces
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
var user = { firstName: "Jane", lastName: "User" };
Typescript inheritanceclass Animal {
constructor(public name: string) { }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the
Palomino");
sam.move();
tom.move(34);
![Page 38: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/38.jpg)
Typescript Generics Modules
class Greeter<T> {
greeting: T;
constructor(message: T) {
this.greeting = message;
}
greet() {
return this.greeting;
}
}
let greeter = new Greeter<string>("Hello, world");
Typescript Decorators • Decorators are an experimental feature that may change in future releases.
• To enable experimental support for decorators
– tsc --target ES5 --experimentalDecorators
– Or edit tsconfig.json
angular-cli will set it for you
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
![Page 39: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/39.jpg)
Typescript Tools
https://www.typescriptlang.org/docs/handbo
ok/integrating-with-build-tools.html
Angular 2 behind the hood
• Angular 2 architecture
• How angular 2 works
• The application
• The model
• The components
• The component decorator
• Putting it all together
![Page 40: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/40.jpg)
Angular 2 architecture
How angular 2 works
• Angular 2 application is made up of Components
• Components is a way to teach the browser new
tags.
• Demo...
![Page 41: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/41.jpg)
The Angular 2 Application
• An Angular 2 Application is a tree of Components
• At the root of that tree, the top level Component is the application
itself.
• The browser will render the top level Component when booting
(bootstrapping) the app.
• You can composite a large Components from from smaller ones.
• When a Component is rendered
– it recursively renders its children Components
Angular 2 Model
• Angular 2 supports many different kinds of models (and data architectures).
– AJAX HTTP Requests
– Websockets
– Indexdb
– LocalStorage
– Service Workers
– Etc….
• MVC, MVVM, MVW
• FLUX
• Observables
![Page 42: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/42.jpg)
Angular 2 Model - Observables
• Observables
– Observables give us streams of data.
– We subscribe to the streams and then perform
operations to react to changes.
– RxJs is the most popular reactive streams library for
Data Architecture in Angular 2
Angular 2 Components
• DEMO
![Page 43: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/43.jpg)
Component Decorator
• DEMO
Demo
• Building your first Angular 2 Application
– Application
– Components
– Models
– Services
![Page 44: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/44.jpg)
Angular CLI commands
ng serve -- prod
![Page 45: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/45.jpg)
introduction - node.js never sleep
node.js
console.log("shalom");
setTimeout(function(){
console.log("ol
am");
}, 2000);
php
echo("shalom");
sleep (2000);
echo("olam");
php
echo("shalom");
sleep (2000);
echo("olam");
No mutax, No possibility to halt an execution.
,
OS un-schedule the work. CPU use goes to “0” and then schedule again after 2 sec.
just idle, Node is good in Ideling
![Page 46: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/46.jpg)
demo
var http = require("http");
var s = http.createServer(function(req,res){
res.writeHead(200, {'content-type':'text/plain'});
res.end("shalom olam\n");
});
s.listen(8000);
Connection →keep-alive
Date →Sun, 15 Nov 2015 14:18:14 GMT
Transfer-Encoding → chunked
content-type → text/plain
HTTP 1.1 - Chunked transfer encoding
Chunked transfer encoding is a data transfer mechanism in version 1.1 of the Hypertext Transfer
Protocol (HTTP) in which data is sent in a series of "chunks". It uses the Transfer-Encoding HTTP
header in place of the Content-Length header, which the earlier version of the protocol would
otherwise require.[1] Because the Content-Length header is not used, the sender does not need to
know the length of the content before it starts transmitting a response to the receiver. Senders can
begin transmitting dynamically-generated content before knowing the total size of that content.
![Page 47: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/47.jpg)
Concurrency Benchmark (1 of 2)
C:\Users\yair>ab -n 100 -c 100 http://localhost:8000/
This is ApacheBench, Version 2.3 <$Revision: 1706008 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient).....done
Server Software:
Server Hostname: localhost
Server Port: 8000
Document Path: /
Document Length: 12 bytes
Concurrency Level: 100
Time taken for tests: 2.040 seconds
Complete requests: 100
Failed requests: 0
Total transferred: 11300 bytes
HTML transferred: 1200 bytes
Requests per second: 49.02 [#/sec] (mean)
Time per request: 2040.117 [ms] (mean)
Concurrency Benchmark (2 of 2)
Time per request: 20.401 [ms] (mean, across all concurrent requests)
Transfer rate: 5.41 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.4 0 2
Processing: 2005 2012 3.3 2013 2018
Waiting: 10 17 4.5 16 26
Total: 2005 2012 3.3 2013 2018
Percentage of the requests served within a certain time (ms)
50% 2013
66% 2013
75% 2014
80% 2014
90% 2015
95% 2017
98% 2018
99% 2018
100% 2018 (longest request)
![Page 48: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/48.jpg)
The V8 JavaScript Engine
watch the video
https://www.youtube.com/watch?v=hWhMKalEicY
npm - packages
• packages people ‘npm install’ a lot
• most dependent-upon packages
![Page 49: Jscript Hotspots – AngularJS,Angular2, ReactJS, - John …marketing.johnbryce.co.il/ad/2016/devgeekweek/43172.pdf · Jscript Hotspots –AngularJS,Angular2, ReactJS, Node.js & more](https://reader034.vdocuments.net/reader034/viewer/2022042620/5a84a52f7f8b9a14748b88f3/html5/thumbnails/49.jpg)
node.js presentation
http://www.tutorialspoint.com/nodejs/nodejs_tutorial.pdf