Tuesday, March 15, 2016

6 Ways to Bind JavaScript’s this Keyword in React, ES6 & ES7

Javascript's this keyword is the source of a lot of confusion for many developers every single day. Unlike a language with a rigid class model, it's not always clear what this is going to refer to in your code, especially when dealing with callback functions, whose callsites you have no control over.

It's trivial for some other code to rebind the context of the function you're working with―using the new keyword and some of the methods that are built onto Function.prototype. This introduces an entire class of confusing scenarios and often you'll see callback driven code scattered with calls to .bind(this).

The Problem

Because React uses the this keyword to reference the component context inside each class, it also inherits this confusion. You're probably used to seeing code like this inside React components.

this.setState({ loading: true });

fetch('/').then(function loaded() {
  this.setState({ loading: false });
});

This code results in a TypeError because this.setState is not a function. This is because when the callback to the promise is called, the internal context of the function is changed and this references the wrong object. Let's take a look at the ways in which we can prevent this from happening.

The Options

Some of these alternatives are old techniques that have been used in Javascript for years, others are specific to React and some won't even work in browsers yet, but we'll explore them all anyway.

1. Alias This

This is approach has been around for a lot longer than React and it involves creating a second reference to the this at the top level of the component's scope.

var component = this;
component.setState({ loading: true });

fetch('/').then(function loaded() {
  component.setState({ loading: false });
});

This approach is lightweight and very easy to understand for beginners (although it may not be clear why you did it). It gives you a visual guarantee that you'll be referring to the correct context.

It feels a bit like you're working against the semantics of the language itself, but it's a simple solution and it works well.

2. Bind This

The next option we have involves injecting the correct context into our callback function at runtime.

this.setState({ loading: true });

fetch('/').then(function loaded() {
  this.setState({ loading: false });
}.bind(this));

All functions in Javascript have a bind method, which allow you to specify the value for this. Once a function has been "bound" the context can't be overriden, meaning that we have a guarantee that this will refer to the correct thing.

This approach is a little bit harder to understand for other programmers and if you're working with deeply nested, asynchronous code, then you'll find yourself having to remember to bind each function as you go.

3. React Component Methods

React allows you to define arbitrary methods on your component classes and these methods are automatically bound with the correct context for this when you create your components with React.createClass. This allows you move your callback code out onto your component.

React.createClass({
  componentWillMount: function() {
    this.setState({ loading: true });

    fetch('/').then(this.loaded);
  },
  loaded: function loaded() {
    this.setState({ loading: false });
  }
});

This can be a very elegant solution if you aren't doing much work in your component (you probably shouldn't be, either!). It allows you to use named functions, flatten your code and forget about having the correct context. In fact, if you try to .bind(this) onto a component method, then React will warn you that you're doing unnecessary work.

Continue reading %6 Ways to Bind JavaScript’s this Keyword in React, ES6 & ES7%


by Dan Prince via SitePoint

Using the WordPress Theme Customizer Media Controls

With recent WordPress updates, its API has changed. Some functions and classes have been added, others have been deprecated.

In this article, I will discuss the Theme Customizer Media Controls. In the previous versions, these controls were available, but only in the WP_Customize_Upload_Control class. Now we find a new class to manage media WP_Customize_Media_Control.

First, I'll cover how to use this new class to manage media controls in the Theme Customizer. Then we will cover a concrete example of a class that extends WP_Customize_Media_Control to allow the control of cropped images.

The New Base Class to Manage a Media Control

Why Introduce a New Class?

Before version 4.3, WordPress provided us WP_Customize_Upload_Control, a class to manage the upload of a media file in the Theme Customizer. However, this class didn’t save the ID of the uploaded media but only its URL. As the ID is a more common way to retrieve information about a media file, the decision was taken to provide a new class, WP_Customize_Media_Control.

If you have the habit of using WP_Customize_Upload_Control, you can still use it without any problems, as it now extends the WP_Customize_Media_Control class so compatibility is ensured. However, it surely is a better idea to update your code and use WP_Customize_Media_Control.

Continue reading %Using the WordPress Theme Customizer Media Controls%


by Jérémy Heleine via SitePoint

A Practical Introduction to Material Design Lite by Google

In 2014 Google published the Material Design specification, a visual language aiming to bring together solid design principles, a consistent user experience across different platforms and devices, and technological and scientific innovation.

July 2015 saw Google release Material Design Lite, a front-end library designed to make it easier to add the material design look and feel to a website.

In this article I’m focusing on the following fundamental principles and components of material design and how you can implement them using the Material Design Lite (MDL) library:

  • Typography
  • Color
  • Layout
  • Cards

[author_more]

The Demo Project

The demo project for this article is called Kaptain Kitty. It’s an HTML template aiming to illustrate how you can apply the material design concepts and MDL components I discuss in this article to a web page.

If you’d like to put Material Design Lite to its paces as you dive into the article, you’ll need your favorite code editor and a modern up-to-date browser.

You can view the demo project and its source code on CodePen:

See the Pen Demo Template Using Material Design Lite by SitePoint (@SitePoint) on CodePen.

Let’s begin.

Including Material Design Lite in Your Project

When it comes to including MDL in your project, you have the following options:

  • Load the necessary CSS and JavaScript files using [Google’s CDN] (Content Delivery Network).
  • Download the minified CSS and JavaScript files and host them on your server.
  • Download and build the source code from the MDL project on GitHub.
  • If you use Bower to manage your project, you can type the following command to install the MDL library files in the bower_components folder: bower install material-design-lite --save
  • If npm is your package manager of choice, run the following command to install the MDL files in the node_modules folder: npm install material-design-lite --save

Google recommends using the CSS and JavaScript files hosted on their CDN. This is the method you’ll find in the demo page for this article.

First off, in the <head> section of your HTML document, include references to the MDL CSS file, Google’s Material Design icons, and the project’s stylesheet, where you’re going to add your own customizations:

[code language="html"]
<link rel="stylesheet"
href="http://ift.tt/1NxWSAi">
<link rel="stylesheet"
href="http://ift.tt/1I7E37E">
<link rel="stylesheet" href="css/styles.css">
[/code]

Next, just before the closing </body> tag, add a reference to the MDL JavaScript file:

[code language="html"]
<script src="http://ift.tt/1TlJTcp">
</script>
[/code]

Typography in Material Design Lite

Material Design’s chosen typefaces for English and English-like languages (Latin, Greek, and Cyrillic characters) are Roboto and Noto.

Noto also supports dense scripts like Chinese, Japanese, and Korean, and tall scripts like Southeast Asian and Middle Eastern languages, e.g., Arabic, Hindi, etc.

To include the Roboto font files in your project, add the following <link> tag at the top of the <head> section of your HTML document:

[code language="html"]
<link rel="stylesheet"
href="http://ift.tt/1nLUIYD">
[/code]

For Latin, Greek, and Cyrillic characters, the material design specification recommends a typographic scale of 12, 14, 16, 20, and 34. You can apply the material design typography principles using MDL by adding a set of specific classes to the markup.

For instance, adding .mdl-typography--display-2 to an <h1> tag and .mdl-typography--display-1 to a <p> tag, adds a font size value of 45px and 34px, respectively:

[code language="html"]
<h1 class="mdl-typography--display-2">Title</h1>
<p class="mdl-typography--display-1">
Sub-title
</p>
[/code]

Classes for typography on the demo project

MDL has a number of classes with typographic scale, accessibility, and readability principles baked in. This makes it easier to display beautiful text content that is pleasant to read irrespective of the device being used to access it.

For a complete list of typography classes, visit the MDL typography component page on GitHub.

Choosing a Color for your MDL Project

Take note of the MDL library stylesheet filename: material.indigo-pink.min.css. The name points to the Material Design color palette implemented in the stylesheet. The default color palette uses indigo as primary color and pink as accent color. But you’re not stuck with these. Below are material design’s recommendations on how to work out a custom color palette and how to implement it using MDL.

Material Design Color Principles

Material design loves combining bold and muted colors, shadows, and highlights:

Color should be unexpected and vibrant.
Google Material Design Spec

However, this doesn’t amount to splashing random colors on your web page. Quite the opposite.

Material design offers a wide range of beautiful color palettes that work harmoniously together. To make it easier to pick colors, each color in a palette has a number label as well as the hexadecimal color value to identify it. Material design guidelines indicate the 500 colors as primary colors. The other colors are best used as accent colors.

When you work out a custom color selection for your website, material design recommends that you pick three hues from the primary palette and one accent color from the secondary palette. Here’s an example:

Material design color palette selection example

Limit the use of accent colors to links, your primary action button, and some components like switches and sliders. Avoid using accent colors for body text:

Discouraged use of accent color on body text

Also, the material design guidelines discourage using the accent colors in large areas of the page and in app bars. Especially important is not to use the same color for both the floating action button and the background:

Discouraged use of accent color in app bar or large areas

Now that you have a solid understanding of material design color guidelines, it’s time to make an awesome color selection for your MDL project. Here’s how.

Continue reading %A Practical Introduction to Material Design Lite by Google%


by Maria Antonietta Perna via SitePoint

Retrofit, a Simple HTTP Client for Android and Java

Exchanging data between a mobile app and a backend server is an essential need for many development projects. Whilst the task became simpler with Google’s Volley library, it has a steep learning curve and Retrofit aims to make the task even simpler.

In this tutorial I will show you how exchange data between an Android app and a backend PHP application using the retrofit library. This sample application will simulate a login process by sending two strings (username and password) to the server, waiting for a response, and then show it to the user.

You can find the final code for this application on GitHub.

Continue reading %Retrofit, a Simple HTTP Client for Android and Java%


by Theodhor Pandeli via SitePoint

ADAM – Creative Multi Page Template

ADAM – Creative Multi Page Portfolio Template is a very clean and modern designed HTML5 multipurpose template for all creative people and agency / creative business. This template is for sale at ThemeForest.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

Tango – Landing Page

Tango is a Multi-Purpose HTML landing page template with real flexibility and customization. Both lead-gen and click through purpose are available. We hope you like it!


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery

HostZyro

HostZyro offers Domain name registration, Web Hosting, Email, Web Security, Website Builder and Logo Design at an affordable price.


by csreladm via CSSREEL | CSS Website Awards | World best websites | website design awards | CSS Gallery