JavaScript Design Patterns: The Observer Pattern

In JavaScript, there is a problem that comes up often. You need a way to update parts of a page in response to certain events, with the data these provide. Say, for example, user input that you then project into one or many components. This leads into a lot of push-and-pull in the code to keep everything in sync.
This is where the observer design pattern can help — it enables one-to-many data binding between elements. This one-way data binding can be event driven. With this pattern, you can build reusable code that solves for your specific needs.
In this article, I’d like to explore the observer design pattern. It will help you solve a common problem you see in client-side scripting. That is one-to-many, one-way, and event-driven data binding. It is a problem that comes up often when you have many elements that must be in sync.
I’ll use ECMAScript 6 to illustrate the pattern. Yes, there will be classes, arrow functions, and constants. Feel free to explore these topics on your own if you are not already familiar. I’ll use parts of ES6 that introduce syntactic sugar only, so it is portable with ES5 if need be.
And I’ll use Test-Driven-Development (TDD) to work on the pattern. This way you have a way knowing how each component is useful.
The new language features in ES6 make for some succinct code. So, let’s get started.
The Event Observer
A high-level view of the pattern looks like this:
EventObserver

├── subscribe: adds new observable events

├── unsubscribe: removes observable events
|
└── broadcast: executes all events with bound data

After I flesh out the observer pattern I’ll add a word count that uses it. The word count component will take this observer and bring it all together.
To initialize the EventObserver do:
class EventObserver {
constructor() {
this.observers = [];
}
}

Start with an empty list of observed events, and do this for every new instance. From now on, let’s add more methods inside EventObserver to flesh out the design pattern.
The Subscribe Method
To add new events do:
subscribe(fn) {
this.observers.push(fn);
}

Grab the list of observed events and push a new item to the array. The list of events is a list of callback functions.
One way to test this method in plain JavaScript is as follows:
// Arrange
const observer = new EventObserver();
const fn = () => {};

// Act
observer.subscribe(fn);

// Assert
assert.strictEqual(observer.observers.length, 1);

I use Node assertions to test this component in Node. The exact same assertions exist as Chai assertions too.
Note the list of observed events consists of humble callbacks. We then check the length of the list and assert that the callback is on the list.
The Unsubscribe Method
To remove events do:
unsubscribe(fn) {
this.observers = this.observers.filter((subscriber) => subscriber !== fn);
}

Continue reading %JavaScript Design Patterns: The Observer Pattern%

Link: https://www.sitepoint.com/javascript-design-patterns-observer-pattern/

A Beginner’s Guide to HTML5 Cross-Browser Polyfills

The web can seem fast moving. New frameworks, tools, and even languages come and go. Yet many developers feel that they have to move as fast as their slowest user. New browsers are ‘evergreen’ — they auto-update unseen in the background without asking for permission, and they’re making leaps and bounds in terms of progressing new APIs.
Yet even modern browsers implement features at different times. It’s frustrating to read about the bleeding-edge of modern development only to think it’s all unusable for years to come. Maybe you’ve looked through your site’s analytics and spotted users still on IE9? Should you code like it’s 2011 or delegate everything to jQuery or some framework? There is another option. Enter the polyfill.
What Are Polyfills and Why Do We Need Them?
Remy Sharp coined the term in a 2009 book and blog post. If the feature exists in the browser, the polyfill lets the browser do its thing, if not, the polyfill steps in to plug the missing functionality. They fill in the holes of older browsers, the missing features we want to use today. It replicates a native API with non-native code.
What Missing Features Are We Talking About?
In 2009, the 5th Edition of ECMAScript landed. It was a large and radical step forward for the language. ECMAScript 2015 delivered a similarly seismic update. Going forward, improvements to the language will be incremental, happening on a yearly basis. It’s an exciting time, with new features continually making their way into the language. Besides the core language itself, there’s also the DOM and the various APIs of the web platform.
To highlight the discrepancy between a modern and a legacy browser, here’s a comparison of the latest Chrome release versus Internet Explorer 9 (which some companies still sadly mandate support for). And here’s a table showing support for ECMAScript 6. The second table only goes as far back as IE 11, which as you can see supports practically zero ES6 features. That’s a lot of missing features…
Polyfills vs Transpiling
So clearly, from looking at the above tables, we need to transpile our code. It takes your shiny new syntax and spits out plain old-fashioned ECMAScript 5. If you want to utilize arrow functions, async/await, rest and spread parameters, classes, et al in your code, you need to transpile your ES6 code into ES5 with a tool such as Babel.
However, you can’t polyfill the syntax of JavaScript. While Babel will take your arrow functions and turn them into regular functions, a polyfill will add methods to the global scope and to native prototypes. Babel offers its own ES6 polyfill that, in the words of the Babel website, offers “new built-ins like Promise or WeakMap, static methods like Array.from or Object.assign, instance methods like Array.prototype.includes, and generator functions."
So the Babel polyfill can give us all the ES6 features we want. But there’s plenty it leaves out. Maybe you add and remove classes with the classList API or conduct media queries with matchMedia, but you still need to support IE9. Luckily there’s a service that provides everything the Babel polyfill covers, and a whole lot more.
Continue reading %A Beginner’s Guide to HTML5 Cross-Browser Polyfills%

Link: https://www.sitepoint.com/html5-cross-browser-polyfills/

6 jQuery-inspired Native DOM Manipulation Methods You Should Know

When jQuery was released, one of the main reasons behind its meteoric rise to popularity was the ease with which it could select DOM elements, traverse them and modify their content. But that was way back in 2006. In those days we were stuck with Internet Explorer 7 and ECMAScript 5 was still a couple of years off.

Luckily, a lot has changed since then. Browsers have become considerably more standards compliant and native JavaScript has improved in leaps and bounds. And as things have improved, we have seen people questioning whether we still need jQuery. I’m not going to get into that argument here, rather I’d like to offer some food for thought, as I present six native DOM manipulation methods which were inspired by this great library. These are as follows:

append()
prepend()
after()
before()
replaceWith()
remove()

In this article I want to examine the similarities and the differences between these native DOM manipulation methods and their jQuery counterparts. Then hopefully, the next time you find yourself including jQuery for the sake of a convenience method or two, you might opt to embrace the power of vanilla JavaScript instead.
1. append()
The append method performs an insertion operation, that is, it adds nodes to the DOM tree. As the name indicates, it appends the passed arguments to the list of children of the node on which it is invoked. Consider the following example:
const parent = document.createElement(‘div’)
const child1 = document.createElement(‘h1’)
parent.append(child1)
parent.outerHTML
//

<h1></h1></div>

const child2 = document.createElement(‘h2’)
parent.append(child2)
parent.outerHTML
// <div><h1></h1><h2></h2></div>

At this point you would be forgiven for asking how this differs from the native appendChild method. Well, a first distinction is that append() can take multiple arguments at once, and the respective nodes will be appended to the list of children, just like the jQuery append method. Continuing the previous snippet:
const child3 = document.createElement(‘p’)
const child4 = document.createElement(‘p’)
const child5 = document.createElement(‘p’)
parent.append(child3, child4, child5)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
</div>
*/

Furthermore, an argument can be even a string. So, while with appendChild() a rather verbose syntax must be employed:
parent.appendChild(document.createTextNode(‘just some text’))

with append() the same operation is shorter:
parent.append(‘just some text’)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
just some text
</div>
*/

The string is converted to a Text node, so any HTML is not parsed:
parent.append(‘<p>foo</p>’)
parent.outerHTML
/* Outputs:
<div>
<h1></h1>
<h2></h2>
<p></p>
<p></p>
<p></p>
just some text
<p&gt;foo&lt;/p&gt;
</div>
*/

This is in contrast to the jQuery method, where strings of markup are parsed and the corresponding nodes are generated and inserted into the DOM tree.
As is usually the case, if the appended node it is already present in the tree, it is first removed from its old position:
const myParent = document.createElement(‘div’)
const child = document.createElement(‘h1’)
myParent.append(child)
const myOtherParent = document.createElement(‘div’)
const myOtherParent.append(child)
myOtherParent.outerHTML
// <div><h1></h1></div>

myParent.outerHTML
// <div></div>”

A final difference between append() and appendChild() is that the latter returns the appended node, whereas the former returns undefined.
2. prepend()
The prepend method is very similar to append(). Children are added, but this time they are prepended to the list of children of the node on which the method is called, just before the first child:
const parent = document.createElement(‘div’)
const child1 = document.createElement(‘p’)
parent.prepend(child1)
parent.outerHTML
// <div><p></p></div>

const child2 = document.createElement(‘h2’)
parent.prepend(‘just some text’, child2)
parent.outerHTML
/* Outputs:
<div>
just some text
<h2></h2>
<p></p>
</div>
*/

The return value of the method is undefined. The corresponding jQuery method is prepend().
3. after()
The after method is another insertion method, but this time it must be called on a child node, that is, a node with a definite parent. Nodes are inserted as adjacent siblings, as can be seen in the following example:
const parent = document.createElement(‘ul’)
const child = document.createElement(‘li’)
child.append(‘First item’)
parent.append(child)
child.after(document.createElement(‘li’))
parent.outerHTML
// <ul><li>First item</li><li></li></ul>

The return value is undefined and in jQuery the similar operation is after().
4. before()
The before method is similar to after(), but now the nodes are inserted before the child node:
const parent = document.createElement(‘ul’)
const child = document.createElement(‘li’)
child.append(‘First item’)
parent.append(child)

const child1 = document.createElement(‘li’)
child1.append(‘Second item’)

const child2 = document.createElement(‘li’)
child2.append(‘Third item’)

child.before(child1, child2)

parent.outerHTML
/* Outputs:
<ul>
<li>Second item</li>
<li>Third item</li>
<li>First item</li>
</ul>
*/

Once again, the return value is undefined. The respective jQuery method is before().
Continue reading %6 jQuery-inspired Native DOM Manipulation Methods You Should Know%

Link: https://www.sitepoint.com/native-dom-manipulation-methods/

Introduction to date-fns – a Lightweight JavaScript Date Library

Working with dates in JavaScript is a pain. Native date methods are often verbose and occasionally inconsistent — something which also makes them error-prone. But good news is at hand. There are several libraries that exist to take the pain out of date manipulation. These libraries are to JavaScript dates, what jQuery is to the native DOM API.
Let me give you an example. This is the accepted answer to a Stack Overflow question asking how to get last day of the month:
var t = new Date();
alert( new Date(t.getFullYear(), t.getMonth() + 1, 0, 23, 59, 59) );

Of course that works, but it’s not immediately obvious what the numbers after getMonth represent. Now contrast that with the considerably more readable:
const today = new Date();
console.log( lastDayOfMonth(today) );

That lastDayOfMonth method is one provided by date-fns, a self-proclaimed comprehensive toolset for manipulating JavaScript dates in the browser and Node.js.
In this article I’m going to show you how to get up and running with date-fns. After reading you’ll be able to drop it into your projects and take advantage of its many helper methods to manipulate dates with ease. This will make code like t.getMonth() + 1, 0, 23, 59, 59 a thing of the past.
So, Why Not Just Use Moment.js?
The elephant in the room is Moment.js. This library has undoubtedly become the de-facto standard for working with dates in JavaScript. So why not use that? Why do we need another JavaScript date library?
Well, according to Sasha Koss, the creator of date-fns, Moment.js has a few inherent problems which motivated him to create date-fns. Sasha expands on what these problems are on the project’s GitHub page, but in a nutshell:

Moment.js is mutable which can cause bugs.
It has a complex OOP API (which doubles the mutability problem).
It has a performance overhead due to the complex API.
Its build size is large when used with Webpack, as locale files are included as part of the bundle.

Let’s contrast that with date-fns (taken from the project’s homepage):

Date-fns is immutable, always returning a new date instead of changing the one you pass in.
It has a simple API. You always have one function that does one thing.
It is fast. You can be sure that your users will have the best user experience.
It is the perfect companion for Webpack. With the function-per-file style you can pick just what you need and stop bloating your project with useless functionality.

For me, the feature that makes it shine is its ease of use. When using it on a web-based project, you can just grab date-fns from a CDN, drop it into your page and profit. More about that next…
Installation
There are a variety of ways to install the library.
It’s available as an npm package:
npm install date-fns –save

Or via Yarn:
yarn add date-fns

Or Bower:
bower install date-fns

Or from a CDN: