Search code examples
polymerpolymer-1.0composition

How to share functionality between Polymer elements in the right way?


Polymer behaviors are great. But sometimes I need to share a single function/method across multiple elements. I don't need lifecycle callbacks, declared properties, etc that comes with behaviors.

I do not know the architecture of Polymer well enough to know:

  1. the best way and place (in life-cycle callbacks?) to add shared methods to custom elements
  2. when it is better to extend the Polymer.Base?

Example 1:

Let's say we want to add a method for lazy-listening that will attach event listeners to elements afterNextRender:

Polymer.RenderStatus.afterNextRender(this, function() {
    // add event listeners
});

As Monica explains in Practical lessons from a year of building web components - Google I/O 2016 Polymer's listeners object should be avoided for elements that might be created in large numbers.

Example 2

Following her example, now we want to add ripple effects or control behaviors to elements only when they are hovered/active/focused and remove it when otherwise. This functionality will be needed by many elements.

Example 3, functions from external libraries such as lodash


Solution

  • A short note for my own question for the time being.

    All elements: Polymer.Base

    Polymer uses Base's _addFeature method to extend the Base prototype which is the prototype of all Polymer elements (side note: _addFeature method itself uses Base's extend method internally). This is the deepest level for extending Polymer Elements.

    Specific element type: element constructor object as well as Behaviors

    Behaviors are shared between all elements of a specific type. They are applied in element registration time. And of course methods in the constructor object also goes to element type's proto.

    Specific to an element instance: everything else

    Other methods defined from element creation onward are specific to that element instance. Also if you use Polymer.Base.create(tag, obj), all the properties and methods in the obj will be applied to the created element (using in keyword i.e. no accessors). Hence, that obj could be shared between different element instances depending on the context.

    Conclusion

    The standard way Polymer creators wanted us to share methods (and a lot more) between different element types is using Behaviors. However, if you have a feature that all or most elements use, extending Polymer.Base is a good option.