A Complete Guide to Flexbox

Background

Flexbox layout (Flexible Box) hướng đến việc cung cấp một cách layout hiệu quả hơn, sắp xếp và phân chia không gian giữa các thành phần trong một container, ngay cả khi kích thước của chúng là động hoặc không xác định (đúng như cái tên “flex”)

Ý tưởng chính bên dưới flex layout là cung cấp cho container khả năng điều chỉnh các thành phần bên trong nó (width/height và thứ tự) để sắp xếp một cách tốt nhất các khoảng không gian trống (chủ yếu là để điều chỉnh cho hợp lý tất cả các kiểu hiển thị của các thiết bị và kích thước màn hình). Một flex container có thể mở rộng để lấp đầy các khoảng trống hoặc co lại để tránh việc đè (overflow).

Điểm quan trọng nhất, flex layout là vô hướng, hoàn toàn ngược lại với kiểu layout thông thường (bock sử dụng cho vertically-based, inline dùng cho horizontally-based). Trong khi các làm đó hoạt động tốt cho nhiều trang, nhưng chúng thiếu đi tính linh động để hỗ trợ cho các ứng dụng lớn và phức tạp (đặc biệt khi thay đổi hướng, kích thước, co giãn màn hình …)

Note: Flexbox layout thích hợp cho việc bố trí các thành phần của một ứng dụng và các thành phần quy mô nhỏ, trong khi Grid thích hợp cho việc bố trí các thành phần quy mô lớn

Nguồn: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

JavaScript Module Pattern: In-Depth

The module pattern is a common JavaScript coding pattern. It’s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I’ll review the basics and cover some truly remarkable advanced topics, including one which I think is original.

The Basics

We’ll start out with a simple overview of the module pattern, which has been well-known since Eric Miraglia (of YUI) firstblogged about it three years ago. If you’re already familiar with the module pattern, feel free to skip ahead to “Advanced Patterns”.

Anonymous Closures

This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We’ll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.

(function () {
	// ... all vars and functions are in this scope only
	// still maintains access to all globals
}());

Notice the () around the anonymous function. This is required by the language, since statements that begin with the tokenfunction are always considered to be function declarations. Including () creates a function expression instead.

Global Import

JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it’s used in an assignment, the global is created if it doesn’t already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals. Here’s an example:

(function ($, YAHOO) {
	// now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));

Module Export

Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value. Doing so will complete the basic module pattern, so here’s a complete example:

var MODULE = (function () {
	var my = {},
		privateVariable = 1;

	function privateMethod() {
		// ...
	}

	my.moduleProperty = 1;
	my.moduleMethod = function () {
		// ...
	};

	return my;
}());

Notice that we’ve declared a global module named MODULE, with two public properties: a method namedMODULE.moduleMethod and a variable named MODULE.moduleProperty. In addition, it maintains private internal stateusing the closure of the anonymous function. Also, we can easily import needed globals, using the pattern we learned above.

Advanced Patterns

While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named MODULE.

Augmentation

One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to augment modules. First, we import the module, then we add properties, then we export it. Here’s an example, augmenting our MODULE from above:

var MODULE = (function (my) {
	my.anotherMethod = function () {
		// added method...
	};

	return my;
}(MODULE));

We use the var keyword again for consistency, even though it’s not necessary. After this code has run, our module will have gained a new public method named MODULE.anotherMethod. This augmentation file will also maintain its own private internal state and imports.

Loose Augmentation

While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn’t always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with loose augmentation. Each file should have the following structure:

var MODULE = (function (my) {
	// add capabilities...

	return my;
}(MODULE || {}));

In this pattern, the var statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like LABjs and load all of your module files in parallel, without needing to block.

Tight Augmentation

While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). Tight augmentation implies a set loading order, but allows overrides. Here is a simple example (augmenting our original MODULE):

var MODULE = (function (my) {
	var old_moduleMethod = my.moduleMethod;

	my.moduleMethod = function () {
		// method override, has access to old through old_moduleMethod...
	};

	return my;
}(MODULE));

Here we’ve overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

Cloning and Inheritance

var MODULE_TWO = (function (old) {
	var my = {},
		key;

	for (key in old) {
		if (old.hasOwnProperty(key)) {
			my[key] = old[key];
		}
	}

	var super_moduleMethod = old.moduleMethod;
	my.moduleMethod = function () {
		// override method on the clone, access to super through super_moduleMethod
	};

	return my;
}(MODULE));

This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility. As I’ve written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval. Nevertheless, I’ve included it for completeness.

Cross-File Private State

One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that will maintain private state across all augmentations:

var MODULE = (function (my) {
	var _private = my._private = my._private || {},
		_seal = my._seal = my._seal || function () {
			delete my._private;
			delete my._seal;
			delete my._unseal;
		},
		_unseal = my._unseal = my._unseal || function () {
			my._private = _private;
			my._seal = _seal;
			my._unseal = _unseal;
		};

	// permanent access to _private, _seal, and _unseal

	return my;
}(MODULE || {}));

Any file can set properties on their local variable _private, and it will be immediately available to the others. Once this module has loaded completely, the application should call MODULE._seal(), which will prevent external access to the internal _private. If this module were to be augmented again, further in the application’s lifetime, one of the internal methods, in any file, can call _unseal() before loading the new file, and call _seal() again after it has been executed. This pattern occurred to me today while I was at work, I have not seen this elsewhere. I think this is a very useful pattern, and would have been worth writing about all on its own.

Sub-modules

Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:

MODULE.sub = (function () {
	var my = {};
	// ...

	return my;
}());

While this may have been obvious, I thought it worth including. Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.

Conclusions

Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I’d combine loose augmentation, private state, and sub-modules.

I haven’t touched on performance here at all, but I’d like to put in one quick note: The module pattern is good for performance. It minifies really well, which makes downloading the code faster. Using loose augmentation allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.

To close, here’s an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I’ve left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.

var UTIL = (function (parent, $) {
	var my = parent.ajax = parent.ajax || {};

	my.get = function (url, params, callback) {
		// ok, so I'm cheating a bit :)
		return $.getJSON(url, params, callback);
	};

	// etc...

	return parent;
}(UTIL || {}, jQuery));

5 Great Features In EcmaScript 6 (ES6 Harmony)

EcmaScript is the standardized scripting language that JavaScript (and some other languages, like ActionScript) implement.  If you think EcmaScript is a terrible name, you’re not alone.  Brendan Eich, the original developer of JavaScript, once wrote that the name EcmaScript sounds like a skin disease.  Naming aside, JavaScript is one of the most important languages in existence today.  Every browser has a JavaScript interpreter, JavaScript on the server is becoming ever more popular, and now it’s possible to use JavaScript for desktop (Chrome Apps), nativish mobile (PhoneGap) and native Windows 8 apps.  A new version of EcmaScript will have a broad impact on web development.

The current version of EcmaScript supported in modern browsers is ES5 (with some ES6 support).  ES5 drives a lot of developers mad.  Folks coming from the backend development space find ES5 lacks some pretty basic language features.  As such, several workarounds have emerged.  TypeScript is very popular in the .NET world (and here at Wintellect) and CoffeeScript is kind of a big deal™ in the Ruby community.  Both TypeScript and CoffeeScript provide syntactic sugar on top of ES5 and then are transcompiled into ES5 compliant JavaScript.  ES6 will tackle many of the core language shortcomings addressed in TypeScript and CoffeeScript.

There are quite a few new features in ES6, many still in draft form.  In this post I’ll cover classes, Arrow Functions, Modules, Block Scoping, and Promises.

Classes

There are several options to approximate classes in ES5.  The most common approach is probably the special constructor function like thishttp://jsfiddle.net/noelstieglitz/a5heA/

function Car( make ) { //approximate a class/constructor
   this.make = make;
   this.currentSpeed = 25;
    
   this.printCurrentSpeed = function(){ //expose a function
          console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
    }
}
 
// Instantiate a new car
var moderatelyPricedCar = new Car( "Kia");
moderatelyPricedCar.printCurrentSpeed(); //Kia is going 25 mph.

Approximate no more!  ES6 introduces language support for classes (class keyword), constructors (constructor keyword), and the extend keyword for inheritance.  The developer’s intent is much more clear using the ES6 syntax. http://www.es6fiddle.net/hrut24r0/

class Car {
    constructor(make) { //constructors!
        this.make = make;
      this.currentSpeed = 25;
    }

    printCurrentSpeed(){
          console.log(this.make + ' is going ' + this.currentSpeed + ' mph.');
    }
}

class RaceCar extends Car { //inheritance
    constructor(make, topSpeed) {
        super(make); //call the parent constructor with super
        this.topSpeed = topSpeed;
    }

    goFast(){
          this.currentSpeed = this.topSpeed;
    }
}

let stang = new RaceCar('Mustang', 150);

stang.printCurrentSpeed();
stang.goFast();
stang.printCurrentSpeed();

If you love prototypical inheritance, no need to fret.  You can still use prototypical inheritance in ES6.

Arrow Functions

Many features in ES6 could fundamentally change how new JavaScript applications are architected.  Arrow functions is not going to fundamentally change anything.  Still, it’s one of my favorite features.  Arrow functions provide two features: lexical scoping of the this keyword and less ceremony when defining an anonymous function.

Without arrow functions, every function defines a this value.  No more will you need to reassign this like you have probably done in the next code snippet:

http://jsfiddle.net/noelstieglitz/wfJL5/

function Car() {
  var self = this; //locally assign this that can be closed over
  self.speed = 0;

  setInterval(function goFaster() {
    //this has a different scope, but we can use the self variable to reference the parent "this"
    self.speed += 5;
      console.log('now going: ' + self.speed);
  }, 1000);
}

var car = new Car();

The above snippet could be rewritten as

http://www.es6fiddle.net/hrw5xz4f/

function Car() { //Note, we could use the new Class feature in ES6 instead
  this.speed = 0;

  setInterval(() => {
    this.speed += 5; //this is from Car
    console.log
    console.log('now going: ' + this.speed);
  }, 1000);
}

If you’re a C# developer who has ever used lambda expressions, the syntax will feel very familiar.  Check out the ecmascript.org wiki regarding arrow functions:

Hard to beat C# and CoffeeScript here (we want the unparenthesized single-parameter form as in C#).

TC39 should embrace, clean-up, and extend rather than re-invent or compete with de-facto and nearby de-jure standards.

I can’t agree more.  Here is some ES5 code that will calculate the square of every value in an array and log the value to the consolehttp://jsfiddle.net/noelstieglitz/LLDBp/1/

var x = [0,1,2];
x.map(function (x) { //anonymous function
  console.log(x * x);
});

In comparison, the ES6 arrow function syntax is really clean http://www.es6fiddle.net/hruu11fz/

let x = [0,1,2];
x.map(x => console.log(x * x)); //arrow function

Modules

Modules have the potential to radically change how many JavaScript applications are structured and standardize a best practice in some already modular applications.  Modules in ES6 provide a way to load and manage dependencies via the new import and export keywords.  There are a few good solutions in ES5, namely 3rd party libraries like CommonJS  or node modules.  Modularity is a such an important concept for large applications, that it makes sense to include it as a core language feature.  The goals for ES6 modules are pretty lofty (from the ecmascript wiki, highlight is my own):

  • Obviate need for globals
  • Orthogonality from existing features
  • Smooth refactoring from global code to modular code
  • Smooth interoperability with existing JS module systems like AMD, CommonJS, and Node.js
  • Fast compilation
  • Simplicity and usability
  • Standardized protocol for sharing libraries
  • Compatibility with browser and non-browser environments
  • Easy asynchronous external loading

 

Read more about modules on Axel’s excellent post.  Here is a code snippet from Axel showing how to load a dependent module:

<module>
        import $ from 'lib/jquery';
        var x = 123;

        // The current scope is not global
        console.log('$' in window); // false
        console.log('x' in window); // false

        // `this` still refers to the global object
        console.log(this === window); // true
</module>

Block Scoping

Scoping in JavaScript is confusing for developers with a C/C#/Java background.  Hoisting can add to that confusion.  In ES5, variables are either globally or locally function scoped.  The lack of block scoping has caused confusion in ES5, and resulted in some interesting patterns to achieve block scope.  In ES6, you can use the new let keyword to achieve block scoping. http://www.es6fiddle.net/hrut3qnv/

var num = 0; //globally scoped

for (let i = 0; i < 10; i++) { //i is block scoped
  num += i;
  console.log('value of i in block: ' + i);
}

console.log('Is i defined here?: ' + (typeof i !== 'undefined')); //Is i defined here?: false 

Promises

Promises provide a mechanism to handle the results and errors from asynchronous operations.  You can accomplish the same thing with callbacks, but promises provide improved readability via method chaining and succinct error handling.  Promises are currently used in many JavaScript libraries.  RSVP.js, Q.js, and the $qservice in Angular are just a few of many examples.  Here is an example from the RSVP.js docs:

getJSON("/api/employee/1").then(function(post) {
  return getJSON(post.commentURL);
}).then(function(comments) {  //you could chain multiple then statements
  // proceed with access to employee
}).catch(function(error) { //succinct error handling
  // handle errors in either of the two requests
});

You can also wait for all promises to complete:

var promises = [2, 3, 5, 7, 11, 13].map(function(id){
  return getJSON("/post/" + id + ".json");
});

RSVP.all(promises).then(function(posts) {
  // posts contains an array of results for the given promises
}).catch(function(reason){
  // if any of the promises fails.
});

This pattern will look familiar to those who have written multithreaded C# code (the last example is like the WaitHandle::WaitAll method).  Unfortunately, each library has a slightly different implementation.  It’s confusing to fully grok the Q.js library only to find that the Angular $q service only provides a subset of the same functionality.  ES6 will standardize promises and remove the external dependencies currently required to use promises.  Below is a partial list and description of some of the ES6 promise functionality.  Read more ES6 promises here.

Promise.resolve(value)

I can’t describe it any better than the Mozilla docs: Returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will “follow” that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Promise.cast(value)

This method is really useful if you are dealing with existing functions or services that don’t return a promise.  If the value passed in is a promise, cast returns the value, otherwise the value is coerced to a promise.  Either way, you can deal with the result as a promise.

Promise.race(iterable)

Promise.race returns the first promise in the iterable to resolve. Note the use of arrow functions. :)

http://www.es6fiddle.net/hruy6vlb/

var p1 = new Promise((resolve, reject) => setTimeout(resolve, 400, "one"));
var p2 = new Promise((resolve, reject) => setTimeout(resolve, 200, "two"));
Promise.race([p1, p2]).then(function(value) {
    console.log(value); //two
});

Promise.all(iterable)

The Promise.all method returns a promise when all promises in the iterable have completed.

http://www.es6fiddle.net/hruyss3j/

var p1 = new Promise((resolve, reject) => setTimeout(resolve, 400, "one"));
var p2 = new Promise((resolve, reject) => setTimeout(resolve, 200, "two"));
Promise.all([p1, p2]).then(function(value) {
    console.log(value); //one, two
});

Read more about promises in this fantastic tutorial by Jake Archibald.

Conclusion

Current support for ES6 is quite limited and a lot of the ES6 spec is still in draft form.  We can look forward to these features (and much more) in the near future, but I wouldn’t recommend using them now.  In the meantime, I recommend using TypeScript (or CoffeeScript, or Traceur, or, etc.) to work around some of the current limitations in ES5.