Polymer Behaviors in ES6

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.

Tags: , , , , , , , , , ,

{ 1 comment to read ... please submit second! }

  1. It there a way to add a behavior dynamically in a component or in a behavior? Meaning, adding a behavior after a component/behavior already loaded

{ 0 Pingbacks/Trackbacks }