Sunday, August 26, 2018

Angular custom directive for a input and output element




ref:
https://stackblitz.com/edit/reset-spy-directive?file=app%2Freset-spy.directive.ts

https://stackoverflow.com/questions/49532872/angular-2-custom-directive-for-a-input-element-how-to-detect-a-reset-call

import { Directive, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import {map, pairwise, startWith, filter} from 'rxjs/operators';

@Directive({
  selector: '[resetSpy]',
})
export class ResetSpyDirective  {
  @Output() reset = new EventEmitter<void>();

  subscription: Subscription;

  constructor(private ngControl: NgControl) {  }

  ngOnInit() {
    const reset$ = this.ngControl.control.valueChanges.pipe(
      map(v => this.ngControl.pristine),
      startWith(this.ngControl.pristine),
      pairwise(),
      filter(([from, to]) => !from && to)
    );

    this.subscription = reset$.subscribe(() => this.reset.emit());
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Saturday, August 25, 2018

Apply Styles for all components in angular by setting ViewEncapsulation.None


ref:https://codecraft.tv/courses/angular/components/templates-styles-view-encapsulation/#_viewencapsulation_none


Templates, Styles & View Encapsulation

Learning Objectives

We’ve covered the basics of the @Component decorator in the quickstart. We explained how decorators work and both the template and selector configuration properties of the @Component decorator.
In this lecture we will go through a number of other configuration properties including templateUrlstylesstyleUrls and encapsulation.
In the section on Dependency Injection we will cover two other ways of configuring Components with the providers and viewProviders properties.

templateURL

We don’t have to write our template code inline with our component code. We can store our HTMLtemplate files separately and just refer to them in our component by using the templateUrl property.
Using the joke application we built in the quickstart, lets move the template for the JokeFormComponentto a file called joke-form-component.html, like so:
Copy@Component({
  selector: 'joke-form',
  templateUrl: 'joke-form-component.html' 
})
class JokeFormComponent {
  @Output() jokeCreated = new EventEmitter<Joke>();

  createJoke(setup: string, punchline: string) {
    this.jokeCreated.emit(new Joke(setup, punchline));
  }
}
We point our component to an external template file by using the templateUrl property.

styles

We can also specify any custom css styles for our component with the styles property.
styles takes an array of strings and just like template we can use multi-line strings with back-ticks.
Let’s define a style for the JokeFormComponent so it gives it a background color of gray.
Copy@Component({
  selector: 'joke-form',
  template: 'joke-form-component.html',
  styles: [
    `
    .card {
      background-color: gray;
    }
    `
  ],
})
class JokeFormComponent {
  @Output() jokeCreated = new EventEmitter<Joke>();

  createJoke(setup: string, punchline: string) {
    this.jokeCreated.emit(new Joke(setup, punchline));
  }
}

Important

The styles property above takes an array of strings, each string can contain any number of CSSdeclarations.
The form component in our application now turns gray, like so:
Component

View Encapsulation

Even though we changed the background color of .card and we have multiple cards on the page only the form component card was rendered with a gray background.
Normally if we change a css class the effect is seen throughout an application, something special is happening here and it’s called View Encapsulation.
Angular is inspired from Web Components, a core feature of which is the shadow DOM.
The shadow DOM lets us include styles into Web Components without letting them leak outside the component’s scope.
Angular also provides this feature for Components and we can control it with the encapsulationproperty.
The valid values for this config property are:
  • ViewEncapsulation.Native
  • ViewEncapsulation.Emulated
  • ViewEncapsulation.None.
The default value is ViewEncapsulation.Emulated and that is the behaviour we are currently seeing.

ViewEncapsulation.Emulated

Let’s inspect the form element with our browsers developer tools to investigate what’s going on.
By looking at the DOM for our JokeFormComponent we can see that Angular added some automaticallygenerated attributes, like so.
encapsulation emulated html
Specifically it added an attribute called _ngcontent-qwe-3.
The other components on the page don’t have these automatically generated attributes, only the JokeFormComponent which is the only component where we specified some styles.
Again by looking at the styles tab in our developer tools we can see a style is set for _ngcontent-qwe-3 like so:
encapsulation emulated css

Note

The css selector .card[_ngcontent-qwe-3] targets only the JokeFormComponent since that is the only component with a html attribute of _ngcontent-qwe-3.
In the ViewEncapsulation.Emulated mode Angular changes our generic css class selector to one that target just a single component type by using automatically generated attributes.
This is the reason that only the JokeFormComponent is gray despite the fact that we use the same card class for all the other JokeComponents as well.
Any styles we define on a component don’t leak out to the rest of the application but with ViewEncapsulation.Emulated our component still inherits global styles from twitter bootstrap.
Our JokeFormComponent still gets the global card styles from twitter bootstrap and the encapsulated style from the component itself.

ViewEncapsulation.Native

If we want Angular to use the shadow DOM we can set the encapsulation parameter to use ViewEncapsulation.Native like so:
Copy@Component({
  selector: 'joke-form',
  templateUrl: 'joke-form-component.html',
  styles: [
    `
    .card {
      background-color: gray;
    }
    `
  ],
  encapsulation: ViewEncapsulation.Native # <!>
})
class JokeFormComponent {
  @Output() jokeCreated = new EventEmitter<Joke>();

  createJoke(setup: string, punchline: string) {
    this.jokeCreated.emit(new Joke(setup, punchline));
  }
}
But now if we look at the application although the background color of the JokeFormComponent is still gray, we’ve lost the global twitter bootstrap styles.
ViewEncapsulation.Native
With ViewEncapsulation.Native styles we set on a component do not leak outside of the components scope. The other cards in our application do not have a gray background despite the fact they all still use the card class.
This is great if we are defining a 3rd party component which we want people to use in isolation. We can describe the look for our component using css styles without any fear that our styles are going to leak out and affect the rest of the application.
However with ViewEncapsulation.Native our component is also isolated from the global styles we’ve defined for our application. So we don’t inherit the twitter bootstrap styles and have to define all the required styles on our component decorator.
Finally ViewEncapsulation.Native requires a feature called the shadow DOM which is not supported by all browsers.

ViewEncapsulation.None

And If we don’t want to have any encapsulation at all, we can use ViewEncapsulation.None.
The resulting application looks like so:
encapsulated none screen
By doing this all the cards are now gray.
If we investigate with our browser’s developer tools we’ll see that Angular added the .card class as a global style in the head section of our HTML.
encapsulated none html
We are not encapsulating anything, the style we defined in our card form component has leaked out and started affecting the other components.

styleURLs

Like the templateUrl property, with the styleUrls property we can externalise the css for our component into another file and include it in.
However like the styles parameter, the styleUrls param takes an array of css files, like so:
Copy@Component({
  selector: 'joke-form',
  templateUrl: 'joke-form-component.html',
  styleUrls: [
   'joke-form-component.css'
  ]
})
class JokeFormComponent {
  @Output() jokeCreated = new EventEmitter<Joke>();

  createJoke(setup: string, punchline: string) {
    this.jokeCreated.emit(new Joke(setup, punchline));
  }
}

Depreciated Properties

Important

If you have seen code that discusses the additional @Component properties; directivespipesinputs and outputs these were in the beta version of Angular and were removed in the final 2.0 release. So the information you’ve read is unfortunately outdated.

Thursday, August 16, 2018

What Javascript can do


Ref: http://jstherightway.org/#js-code-style



JavaScript

The Right Way

Hey, you!

This is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices.
Despite the name, this guide doesn't necessarily mean "the only way" to do JavaScript.
We just gather all the articles, tips, and tricks from top developers and put it here. Since it comes from exceptional folks, we could say that it is "the right way", or the best way to do so.

GETTING STARTED

ABOUT

Created by Netscape in 1995 as an extension of HTML for Netscape Navigator 2.0, JavaScript had as its main function the manipulation of HTML documents and form validation. Before winning this name so famous nowadays, JavaScript was called Mocha. When it first shipped in beta releases, it was officially called LiveScript and finally, when it was released by Sun Microsystems, was baptized with the name by which it is known today. Because of the similar names, people confuse JavaScript with Java. Although both have the lexical structure of programming, they are not the same language. Different from C, C# and Java, JavaScript is an interpreted language. It means that it needs an "interpreter". In case of JavaScript, the interpreter is the browser.

CURRENT VERSION

The JavaScript standard is ECMAScript. As of 2012, all modern browsers fully support ECMAScript 5.1. Older browsers support at least ECMAScript 3. As of June 2015 the spec for ES6/ES2015 has been approved. Following the new annual release cycle, ES7/ES2016 has been adopted in June 2016. See the ECMAScript 2016 Language Specification at Ecma International.
A good reference to versions, references and news about JavaScript can be found at the Mozilla Developer Network.

THE DOM

The Document Object Model (DOM) is an API for HTML and XML documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation by using a scripting language such as JavaScript. See more at Mozilla Developer Network - DOM.

JS CODE STYLE

CONVENTIONS

As every language, JavaScript has many code style guides. Maybe the most used and recommended is the Google Code Style Guide for JavaScript, but we recommend you read Idiomatic.js.

LINTING

Nowadays the best tool for linting your JavaScript code is JSHint. We recommend that whenever possible you verify your code style and patterns with a Lint tool.

THE GOOD PARTS

OBJECT ORIENTED

JavaScript has strong object-oriented programming capabilities, even though some debates have taken place due to the differences in object-oriented JavaScript compared to other languages.

ANONYMOUS FUNCTIONS

Anonymous functions are functions that are dynamically declared at runtime. They’re called anonymous functions because they aren’t given a name in the same way as normal functions.

FUNCTIONS AS FIRST-CLASS OBJECTS

Functions in JavaScript are first class objects. This means that JavaScript functions are just a special type of object that can do all the things that regular objects can do.

LOOSE TYPING

For many front-end developers, JavaScript was their first taste of a scripting and/or interpretive language. To these developers, the concept and implications of loosely typed variables may be second nature. However, the explosive growth in demand for modern web applications has resulted in a growing number of back-end developers that have had to dip their feet into the pool of client-side technologies. Many of these developers are coming from a background of strongly typed languages, such as C# or Java, and are unfamiliar with both the freedom and the potential pitfalls involved in working with loosely typed variables.

SCOPING AND HOISTING

Scoping: In JavaScript, functions are our de facto scope delimiters for declaring vars, which means that usual blocks from loops and conditionals (such as if, for, while, switch and try) DON'T delimit scope, unlike most other languages. Therefore, those blocks will share the same scope as the function which contains them. This way, it might be dangerous to declare vars inside blocks as it would seem the var belongs to that block only.
Hoisting: On runtime, all var and function declarations are moved to the beginning of each function (its scope) - this is known as Hoisting. Having said so, it is a good practice to declare all the vars altogether on the first line, in order to avoid false expectations with a var that got declared late but happened to hold a value before - this is a common problem for programmers coming from languages with block scope.

FUNCTION BINDING

Function binding is most probably the least of your concerns when beginning with JavaScript, but when you realize that you need a solution to the problem of how to keep the context of this within another function, then you might realize that what you actually need is Function.prototype.bind().

CLOSURE FUNCTION

Closures are functions that refer to independent (free) variables. In other words, the function defined in the closure 'remembers' the environment in which it was created in. It is an important concept to understand as it can be useful during development, like emulating private methods. It can also help to learn how to avoid common mistakes, like creating closures in loops.
Source: MDN - Closures

STRICT MODE

ECMAScript 5's strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.

IMMEDIATELY-INVOKED FUNCTION EXPRESSION (IIFE)

An immediately-invoked function expression is a pattern which produces a lexical scope using JavaScript's function scoping. Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.

This pattern has been referred to as a self-executing anonymous function, but @cowboy (Ben Alman) introduced the term IIFE as a more semantically accurate term for the pattern.

MUST SEE


ARINDAM PAUL - JAVASCRIPT VM INTERNALS, EVENTLOOP, ASYNC AND SCOPECHAINS

PATTERNS

DESCRIPTION

While JavaScript contains design patterns that are exclusive to the language, many classical design patterns can also be implemented.
A good way to learn about these is Addy Osmani’s open source book Learning JavaScript Design Patterns, and the links below are (in the majority) based on it.

DESIGN PATTERNS



Creational Design Patterns


Structural Design Patterns


Behavioral Design Patterns

MV* PATTERNS


There are some implementations of the traditional MVC Pattern and its variations in JavaScript.

TESTING TOOLS

DESCRIPTION

Various libraries and frameworks to do tests in JavaScript.

LINKS



Maintained by TJ Holowaychuk


Maintained by jQuery


Maintained by Pivotal Labs


Maintained by the team behind AngularJS. Mostly by Vojta Jina


Maintained by Sitepen


A JavaScript code coverage tool written in JavaScript, maintained by Krishnan Anantheswaran


Standalone test spies, stubs and mocks for JavaScript. No dependencies, works with any unit testing framework. Created by Sinon.JS community


A test helper to mock functions and the XHR object, maintained by Leo Balter


Test runner with asynchronous tests, maintained by Sindre Sorhus


Painless JavaScript Testing, maintained by Facebook

FRAMEWORKS

GENERAL PURPOSE



jQuery is a fast, small, and feature-rich JavaScript library. Built by John Resig.


Built by Yahoo!, YUI is a free, open source JavaScript and CSS library for building richly interactive web applications. New development has stopped since August 29th, 2014.


Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API. If you use jQuery, you already know how to use Zepto.


Dojo is a free, open-source JavaScript toolkit for building high performance web applications. Project sponsors include IBM and SitePen.


Underscore.js is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

MV*



Very popular JavaScript client-side framework, built by @jashkenas.


Built by @wycats, jQuery and Ruby on Rails core developer.


Simplify dynamic JavaScript UIs by applying the Model-View-View Model (MVVM).


Built by Google, Angular.js is like a polyfill for the future of HTML.


One framework.Mobile & desktop. One way to build applications with Angular and reuse your code and abilities to build apps for any deployment target. For web, mobile web, native mobile and native desktop.


Cappuccino is an open-source framework that makes it easy to build desktop-caliber applications that run in a web browser.


JavaScriptMVC is an open-source framework containing the best ideas in jQuery development.


Meteor is an open-source platform for building top-quality web apps in a fraction of the time, whether you're an expert developer or just getting started.


Spice is a super minimal (< 3k) and flexible MVC framework for javascript. Spice was built to be easily added to any existent application and play well with other technologies such as jQuery, pjax, turbolinks, node or whatever else you are using.


Riot is an incredibly fast, powerful yet tiny client side (MV*) library for building large scale web applications. Despite the small size all the building blocks are there: a template engine, router, event library and a strict MVP pattern to keep things organized.


CanJS is a JavaScript framework that makes developing complex applications simple and fast. Easy-to-learn, small, and unassuming of your application structure, but with modern features like custom tags and 2-way binding.

LIBRARY



Built by Facebook. React is a JavaScript library for creating user interfaces by Facebook and Instagram. Many people choose to think of React as the V in MVC.


Is an MVVM library providing two-way data binding, HTML extended behaviour (through directives) and reactive components. By using native add-ons a developer can also have routing, AJAX, a Flux-like state management, form validation and more. Provides a helpful Chrome extension to inspect components built with Vue.


Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.


Asynchronous templates for the browser and node.js.

ANIMATION



GSAP is the fastest full-featured scripted animation tool on the planet. It's even faster than CSS3 animations and transitions in many cases.


Velocity is an animation engine with the same API as jQuery's $.animate().


Bounce.js is a tool and JS library that lets you create beautiful CSS3 powered animations.


A simple but powerful JavaScript library for tweening and animating HTML5 and JavaScript properties.


Move.js is a small JavaScript library making CSS3 backed animation extremely simple and elegant.


SVG is an excellent way to create interactive, resolution-independent vector graphics that will look great on any size screen.


Rekapi is a library for making canvas and DOM animations with JavaScript, as well as CSS @keyframe animations for modern browsers.


Make use of your favicon with badges, images or videos.


Textillate.js combines some awesome libraries to provide a ease-to-use plugin for applying CSS3 animations to any text.


Motio is a small JavaScript library for simple but powerful sprite based animations and panning.


With Anima it's easy to animate over a hundred objects at a time. Each item can have it's mass and viscosity to emulate reallife objects!

GAME ENGINES




MelonJS is a free, light-weight HTML5 game engine. The engine integrates the tiled map format making level design easier.


ImpactJS is one of the more tested-and-true HTML5 game engines with the initial release all the way back at the end of 2010. It is very well maintained and updated, and has a good-sized community backing it. There exists plenty of documentation - even two books on the subject of creating games with the engine.


LimeJS is a HTML5 game framework for building fast, native-experience games for all modern touchscreens and desktop browsers.


Crafty is a game engine that dates back to late 2010. Crafty makes it really easy to get started making JavaScript games.


Cocos2d-html5 is an open-source web 2D game framework, released under MIT License. It is a HTML5 version of Cocos2d-x project. The focus for Cocos2d-html5 development is around making Cocos2d cross platforms between browsers and native application.


Phaser is based heavily on Flixel. It is maintained by Richard Davey (Photon Storm) who has been very active in the HTML5 community for years.


Goo is a 3D JavaScript gaming engine entirely built on WebGL/HTML5


LycheeJS is a JavaScript Game library that offers a complete solution for prototyping and deployment of HTML5 Canvas, WebGL or native OpenGL(ES) based games inside the Web Browser or native environments.


Quintus is an HTML5 game engine designed to be modular and lightweight, with a concise JavaScript-friendly syntax.


Kiwi.js is a fun and friendly Open Source HTML5 Game Engine. Some people call it the WordPress of HTML5 game engines


Panda.js is a HTML5 game engine for mobile and desktop with Canvas and WebGL rendering.


Rot.js is a set of JavaScript libraries, designed to help with a roguelike development in browser environment.


Isogenic is an advanced game engine that provides the most advanced networking and realtime multiplayer functionality available in any HTML 5 game engine. The system is based on entity streaming and includes powerful simulation options and client-side entity interpolation from delta updates.


Super-fast 3D framework for Web Applications & Games. Based on Three.js. Includes integrated physics support and ReactJS integration.

READING

ARTICLES





















BOOKS















































FREE E-BOOKS



PORTALS


HELPERS


npm
 
bower
 
yeoman
grunt
 
gulp
 
brunch
Browser compilation library
 
Webpack
 
Rollup
Browserify
 
todo mvc

function declaration, expression and call/invoke/execution

  The  function  declaration defines a function with the specified parameters. The  function   keyword can be used to define a function ins...