Simplified Partial Application with ES6

Wednesday, April 20th, 2016

When implementing Partial Application in ES6, implementations naturally become quite easier to reason about as default parameters, rest parameters and arrow functions can be leveraged to provide a much more comprehensive implementation.

While on the surface this may appear insignificant, when compared to having relied almost exclusively on the arguments object and Array.prototype to provide the same functionality in ES5, the benefits become rather apparent.

For instance, consider a simple multiply function which, depending on the arity of the invocation, either computes basic multiplication against the provided parameters, or returns a partial application. That is to say, if invoked as a unary function (single argument), the function returns a partial application (a new function which multiplies by the given argument). If invoked as a variadic function (variable amount of arguments), the function returns the product of the arguments.

In ES5, we could implement such a function as follows:

View Pen

Given the above example, in order to inspect and iterate over the provided arguments, we need to rely on the Array.prototype, specifically, we need to invoke Function.prototype.call on Array prototype in order to apply the slice method so as to convert the arguments object to an Array. Additionally, we also have to account for a default value of arguments[0] should it be omitted or NaN.

Not only does this require a superfluous amount of code, but it also results in a more complicated implementation that becomes considerably more verbose, and as a result, more difficult to reason about; especially for developers who may not be familiar with the specific mechanisms employed within the implementation.

ES6 to the rescue …

With the introduction of default parameters, …rest parameters, and Arrow Functions (fat arrows) in ES6, the implementation of the above example can be significantly reduced, and as a result, becomes considerably easier to understand, as we can simply re-write the multiply function as:

View Pen

As can be seen, implementing the multiply function in ES6 not only reduces the SLOC by 1/2 of the previous ES5 implementation, but more importantly, by using rest parameters, it allows us to determine and work with the functions arity in a much more natural way. Moreover, both iterating over the provided arguments and returning the partial application becomes considerably more concise simply by using arrow functions, and the need to account for undefined arguments becomes moot thanks to default parameters.

In addition, variadic invocations of such functions can also be simplified considerably using the ES6 spread operator. For example, in order to pass an Array of arguments to a function in ES5, one would need to call Function.apply against the function, like so:

With ES6 spread operators, however, we can simply invoke the function directly with the given array preceded by the spread operator:

Simple!

Hopefully this article has shed some light on a few of the features available in ES6 which allow for writing implementations which not only read much more naturally, but can be written with considerably less mental overhead.

IIFE in ES6

Wednesday, April 6th, 2016

Unlike ES5, which is syntactically less opinionated, in ES6, when using an IIFE, parenthetical order matters.

For instance, in ES5 an IIFE could be written either as:

or

As can be seen in the above examples, in ES5 one could either wrap and invoke a function expression in parentheses, or wrap the function expression in parentheses and invoke the function outside of the parentheses.

However, in ES6, the former throws an exception, thus, one can not use:

But rather, the invocation must be made outside of the parentheses as follows:

As an aside for those who are curious, the syntax requirements are specific to ES6 and not a by-product of any particular transpilers (i.e. Babel, Traceur, etc.).

Polymer Behaviors in ES6

Friday, March 25th, 2016

Being a typical aspect of Object Oriented Design, inheritance, and mixins, provide the means by which modular reuse patterns can be facilitated within a given system. Similarly, Polymer facilitates code reuse patterns by employing the notion of shared behaviors modules. Let’s take a quick look at how to leverage them in Polymer when using ES6 classes.

Implementing Behaviors

Implementing a Behavior is quite simple, just define an object within a block expression or an IIFE, and expose it via a namespace, or module loader of choice:

some-behaviors.js

Then, include the behavior in a corresponding .html document of the same name so as to allow the behavior to be imported by subsequent elements:

some-behavior.html

Extending Behaviors

After having defined and exposed a given Behavior, the Behavior can then be extended from element classes by defining a behaviors getter / setter as follows:

Once the behavior has been extended, simply import the behavior in the element’s template (or element bundle, etc.) and it is available to the template class:

Try it

Implementing Multiple Behaviors

Similar to individual behaviors, multiple behaviors can also be defined and extended:

first-behavior.js

second-behavior.js

In certain cases, I have found it helpful to group related behaviors together within a new behaviors (array) which bundles the individual behaviors together:

Note: As can be seen in the FourthBehavior, a behavior can also be implemented as an Array of previously defined behaviors.

Extending Multiple Behaviors

As with extending individual behaviors, multiple behaviors can also be extended using a behaviors getter / setter. However, when extending multiple behaviors in ES6, there are syntactic differences which one must take note of. Specifically, the behaviors getter must be implemented as follows:

Try it

And that’s basically all there is to it. Hopefully this article helped outline how Polymer Behaviors can easily be leveraged when implementing elements as ES6 classes. Enjoy.

Property Change Observers in Polymer

Wednesday, January 6th, 2016

When building Web Components the ability to observe property / attribute changes on custom elements and respond to them accordingly can prove quite useful.

Fortunately, Polymer makes this incredibly easy. Let’s take a quick look …
(note, we’ll be using ES6 here)

Single Property Observers

In it’s most basic form, a Single Property Observer can be defined by simply implementing a method and adding it to the property’s observer configuration:

Now, whenever the property changes, Polymer will automatically invoke the observer method; handily passing two arguments: the updated value, and the previous value:

Try it

Pretty cool, right? It gets even better…

Multi-Property Observers

In addition to Single Property Observers, multiple properties can be observed for changes using the observers array:

The observers array is rather self-explanatory: each item is simply a string representation of the method to be invoked with the observed properties specified as arguments:

Try it.

For more information, see multi-property-observers.

Sub-Property Observers

Similar to Multi-Property Observers, sub-properties can be observed as well (e.g. user.username, or user.account.name, etc.). For instance:

Try it

Deep Sub-Property Observers

As with explicit Sub-Property Observers, (n-level) arbitrary sub-properties can be observed using wildcard notation:

Try it.

Both Sub-Property Observers and Deep Sub-Property Observers differ from Single-Property Observers in that a changeRecord is passed to the observer method as opposed to the updated value. A changeRecord is simply an object which contains the following properties (as per the Polymer Docs):

  • changeRecord.path: Path to the property that changed.
  • changeRecord.value: New value of the path that changed.
  • changeRecord.base: The object matching the non-wildcard portion of the path.

It’s important to keep in mind that Sub-Property, and Deep Sub-Property observations can only be made using either property bindings or the set method.

Array Mutation Observers

Complimentary to Single, Multi, Sub, and Deep Property Observers, Polymer provides Array Mutation Observers which allow for observing Array and Array element properties for changes.

This is where the API requires a little getting used to IMHO, and so I would recommend reading the Docs in detail.

That being said, Array Mutation Observers are quite powerful, for example:

Try it.

When observing Arrays, in order for bindings to reflect properly, Polymer’s Array Mutation Methods must be used. This is quite simple in that the API is the same as that of the corresponding Native Array methods, with the only difference being the first argument is the path to the array which is to be modified. For example, rather than: this.items.splice(...) one would simply use: this.splice('items', ...).

Conclusion

Hopefully this simple introduction to Polymer Observers has demonstrated some of the powerful capabilities they provide. Understanding how each can be implemented will certainly simplify the implementation of your custom elements, therefore leveraging them where needed is almost always a good design decision.

Feel free to explore any of the accompanying examples.

Chuck Norris on Polymer

Wednesday, December 16th, 2015

For the past several months I have been evaluating potential frameworks which could facilitate the implementation of context aware Web Components such that each component can be assembled declaratively into recombinant features and higher-level applications. After a focused period of prototyping each candidate framework, Polymer 1.x has proven to be the most effective approach to satisfy these particular design goals, and many others as well.

While I have also been leveraging Angular 2 for implementing self-contained Web Applications which need not be composed outside the scope of the application’s root component / template, the requirement to provide elements which can be arbitrarily composed within an html document declaratively or imperatively independent of using any one particular framework is one which proves somewhat challenging; yet, can easily be satisfied by leveraging Web Components, and Polymer simplifies the process of doing so considerably.

Polymer 1.x

On a high-level, Polymer provides some much welcomed sugaring over the four Web Component specifications; HTML Templates, Shadow DOM, HTML Imports, and Custom Elements, respectively. The higher level abstraction and API offered by Polymer significantly simplifies the process of Web Component development, while reducing the time and effort required to meet both simple and complex use-cases alike.

Features provided out-of-the-box embrace that which developers have come to expect from a modern library or framework, such as one-way and two-way binding annotations, template helpers, a Local and Light DOM API, declarative and imperative event mappings, declared properties with observers and attribute reflection, and much more.

Add to this the growing Catalog of Elements provided by the Polymer Project, a complete Web Component Testing solution via WCT, optimization features such as Vulcanization with tooling support for Gulp, API Documentation components via Iron Component Page (though still pending ES6 Support) concise documentation with easy to use examples, and developers are afforded a rather elegant solution for building high quality, future facing Web Components, today.

In addition, Polymer comes in three specific layers, each of which builds upon the previous lower-level implementation. This allows for a nice level of flexibility in choosing the most appropriate implementation based on your specific needs. Depending on what is required, one can choose from the mirco-implementation for providing basic custom element sugaring, the mini-implementation for more advanced local DOM and life-cycle hooks, and the standard-implementation which provides the full suite of Polymer features.

Given the capabilities Polymer has to offer, as well as the growing number of organizations using Polymer, and some rather interesting applications being built with Polymer, if you haven’t already, I highly recommend given it a try.

Chuck Norris!

So what does any of this have to do Chuck Norris?

Well, nothing actually.

Except, like Chuck Norris, Polymer is cool – very cool, and so after accidentally coming across the ICNCB service, I thought a simple Web Component which displays some comical facts about Chuck Norris could serve as a useful Polymer example.

And so, if you like to laugh a bit while learning something new, feel free to clone the repo over on Github to get familiar with a few of Polymer’s general capabilities, or simply check out the app here and have a few laughs.

Coming up, Chuck Norris on Angular 2 …

NET::ERR_CERT_INVALID Trick

Thursday, October 22nd, 2015

So here is an utterly ridiculous trick that may actually prove to be quite useful should you ever need it.

With recent Chrome updates, hosts which fail to provide a valid SSL certificate are blocked via a NET::ERR_CERT_INVALID error. This essentially is the result of a secure site failing to provide a valid SSL Certificate in some way. In Chrome, when this occurs, you will see a screen similar to the following:

NET::ERR_CERT_INVALID

Previously one could circumvent this by clicking on a link which would allow you to override the error. However, such links in current builds of Chrome are no longer provided.

Interestingly, the work around for this is simple, bordering the ridiculous. Just focus on the page and type “danger“. The page will then automatically refresh and load as if the certificate was valid from that point on.

Obviously you want to be mindful of this work around (e.g. only using it for known hosts, such as a dev environment, etc., as was the case in my example).