Sunday 30 November 2014

React.js Concepts

Overview

React.js is used to create components in your views, it specifically renders UI and responds to events.

Instagram and Facebook have come up with a FrontEnd client library that uses a virtual DOM diff implementation for ultra-high performance.  This works by comparing DOM changes in memory to calculate a patch required to update the DOM:

image

On every data change React re-renders the entire component in memory then uses a diff to apply a patch for what has changed in the DOM.  This means within React the virtual DOM UI is immutable, on each data change it’s completely replaced. 

Here is a stackoverflow comparing Angular’s dirty checking with Reacts virtual dom diffs, with the answer provided by the creator of React:

http://stackoverflow.com/questions/21109361/why-is-reacts-concept-of-virtual-dom-said-to-be-more-performant-than-dirty-mode

image

The syntax is a bit funky but quite simple once you get used to it.  It optionally uses a JSX transform library which is the preferred way of coding with React.  The following examples use JSX.

Concepts

React.createClass:  Creates a component by the developer providing a “render” function.

React.renderComponet:  Renders the component to a specified location

Props (or Properties):  Container object for immutable data, for example used with labels.  This example has two props: now and b.  Now is set to a javascript expression of todays date and b is set to a string literal.

image

Here is a more complex example showing default values, provided to React by using the getDefaultProps function, which are later overwritten by the component usage.

image

 

State:  Container object for mutable data for example used with input controls.  You can provide React the values for the initial state using the getInitialState function.  Here is an example of using state (note: state would usually be used with input controls rather than a label):

image

Controlled control:  Form component rendered with a value (or checked) property e.g.:

image

Mixins:  Common code that can be reused across components

ReactLink:  Used to streamline the updating of state so you don’t have to write your own onChange function to update state set.

image

Uncontrolled controls:  Form components rendered without a value (or checked) prop.  This enables React to ignore the component during the render process, allowing for better performance.  onChange event can still be used to detect changes outside of React.  You can also provide a defaultState value.  Beware, as React will not be tracking this component this will cause divergence from Reacts virtual DOM.

image

Ref:  Similar to the “ID” attribute in HTML, this attribute allows fast access to an item within your component instance:

image

getDOMNode(): Gets the underlying DOM node from an item within a React component instance.

PropType validation: By providing a propTypes property object you can validate your properties.  This example states the now property must be a string and the b property must be great than 5.

image

Flux:  Facebook have a separate optional complimentary library called Flux for single (or uni) directional data flow.  They have done this by introducing a dispatcher and (data) store.

image

The Dispatcher acts as a “traffic controller” for all the actions.

The (data) Store is the data layer that updates whenever it receives a new action from the dispatcher.

Thursday 27 November 2014

Resolve promises in router, defer controllers

Taken from this style guide:  http://toddmotto.com/opinionated-angular-js-styleguide-for-teams/

After creating services, we will likely inject them into a controller, call them and bind any new data that comes in. This becomes problematic of keeping controllers tidy and resolving the right data.

Thankfully, using angular-route.js (or a third party such as ui-router.js) we can use a resolve property to resolve the next view's promises before the page is served to us. This means our controllers are instantiated when all data is available, which means zero function calls.

Bad:
function MainCtrl (SomeService) {

var self = this;

// unresolved
self.something;

// resolved asynchronously
SomeService.doSomething().then(function (response) {
self.something = response;
});

}
angular
.module('app')
.controller('MainCtrl', MainCtrl);

Good:
function config ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
resolve: {
doSomething: function (SomeService) {
return SomeService.doSomething();
}
}
});
}
angular
.module('app')
.config(config);

At this point, our service will internally bind the response of the promise to another Object which we can reference in our "deferred-instantiated" controller:

Good:
function MainCtrl (SomeService) {
// resolved!
this.something = SomeService.something;
}
angular
.module('app')
.controller('MainCtrl', MainCtrl);

We can go one better, however and create a resolve property on our own Controllers to couple the resolves with the Controllers and avoid logic in the router.

Best:
// config with resolve pointing to relevant controller
function config ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main',
resolve: MainCtrl.resolve
});
}
// controller as usual
function MainCtrl (SomeService) {
// resolved!
this.something = SomeService.something;
}
// create the resolved property
MainCtrl.resolve = {
doSomething: function (SomeService) {
return SomeService.doSomething();
}
};

angular
.module('app')
.controller('MainCtrl', MainCtrl)
.config(config);

Route changes and ajax spinners

While the routes are being resolved we want to show the user something to indicate progress. Angular will fire the $routeChangeStart event as we navigate away from the page, which we can show some form of loading and ajax spinner, which can then be removed on the $routeChangeSuccess event (see docs).

Saturday 15 November 2014

Conferences

Quick list of conferences to keep an eye open for:

http://ng-conf.org/ Angular / Google March YouTube
http://ngeurope.org/  Angular / Google October YouTube
http://jsconf.com/ JavaScript Monthly YouTube
http://www.dotjs.eu/ JavaScript November YouTube
http://jqueryuk.com/2015/ jQuery March Vimeo
javascript-summit JS / jQuery November  
http://conf.reactjs.com/ React / Facebook January  
http://www.buildwindows.com/ Microsoft April Channel9
https://anglebrackets.org/ Microsoft May  
http://reactconf.com/ Reactive Systems April and Nov  
https://www.google.com/events/io Google June YouTube
https://developer.apple.com/wwdc/ Apple June Apple
https://fbf8.com/ Facebook April Facebook Live

Friday 14 November 2014

ng-simple-rest-app

Here’s an example of a simple rest application, written to demonstrate simple techniques to get people started with Angular:

Source:  https://github.com/stevenh77/ng-simple-rest-app

Client features
- default page not being shown by the router
- automatic conversion of Json strings into JavaScript dates (generic/aop approach)
- date control bound to model object from a data service
- select control databound to model from a data service
- confirmation dialog
- rest service calls for get, post, put, delete
- bootstrap layout for form
- form validation
- app navigation from controller using location and window services
- logging abstraction
- promises for service calls including error handling
- generic application level error handling
- busy indicator
- unit tests with mocks and promises
- material design for form entry

Server features:
- simple rest endpoints
- compression
- request logging to console
- CORS enabled
- object retrieved from JS array based on key
- object removed from JS array based on key

Wednesday 12 November 2014

Form validation based on Material Design

I’ve extended the Material Design to include some form validation.

I’m undecided about using a valid icon or whether a lack of validation error message implies validity.  Perhaps I’m swayed by years of rubbish UX on the web that I think I’m currently in favour of using an icon.  And if an icon is to be used, how subtle should be it? 

material-design-with-validation-rules

Saturday 8 November 2014

Creating a simple REST API with Node Express

Install dependencies

Create: server.js

Create film-data.json

Start the server

image

image

image

image

You can download and run the full source without the need to install any dependencies:  https://github.com/stevenh77/simple-rest-express-server

Friday 7 November 2014

API Mocking

UI devs love to be able to work independently of server teams, which is where API mocking can really help out.

Quickly knock up a few end points with test data and responses returned – takes no time at all.

Great for building little working prototypes with REST service requests.

Mocky.io

image

Mockable.io

image

Redesign For Virgin America

345buttons

66a789101112131415

Virgin redesign

Wednesday 5 November 2014

Transclude explained

Combination of transfer and include, this simply means you want to take the HTML within the usage of your directive and include it within the template supplied by your directive definition.

image

The key lines are 14, 18 and 30.  These tell Angular I want to transfer the contents of the HTML DOM and here is where I want to include it.  Line 30 is the usage of the directive including the {{text}} which is transcluded.

 

 

image

Angular Services vs Factories vs Providers

The following explanations were taking from various Angular docs, Misko code examples and StackOverflow posts.

What?

image
  • Service returns an instance of the actual function
  • Factory returns function’s return value
  • Provider returns the output of the function’s $get function

       

       

      How?

      When?

      Factory and Service are the most commonly used recipes. The only difference between them is that Service recipe works better for objects of custom type, while Factory can produce JavaScript primitives and functions.

      Factories are an example of the revealing module pattern.

      Providers have the advantage that they can be configured during module configuration phase.

      Under the hood

      Services, Factories as well as Values are all created under the hood using Providers.

      Monday 3 November 2014

      Accordion with active header colour

      I noticed this nice style from a control vendor and have recreated the accordion in a similar style.

      accordion

      Demo: 

      If the animation is struggling in the iframe above check out the demo in a new page:

      http://stevenhollidge.com/blog-source-code/accordion

      Code:

      Floating label

      Material Design from Google has come up with floating labels for form entry.

      The label starts off as the placeholder or watermark for the control, when the user enters the control the label floats above the text in an animation.

      material-design from Steven Hollidge on Vimeo.

      You can hear more about Material Design in this talk https://www.youtube.com/watch?v=2qiyhkQVyxE

      The floating label appear at 12 mins 05 seconds.

      Nice breadcrumb UI

      image

      image

      Ok so the colours need changing but it’s a nice little design.

      Demo:  http://stevenhollidge.com/blog-source-code/breadcrumbs

      Code:

      Angular from scratch

      Basic change detection scope and directives implemented in one page of code, basically it’s Angular without Angular!

      image

      Video: https://www.youtube.com/watch?v=Mk2WwSxK218

      Demo: http://stevenhollidge.com/blog-source-code/angular-from-scratch

      Code: