Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write listeners in ES6 in Polymer?

I basically want to write the following code in ES6 fashion.

 listeners: {
    'neon-animation-finish': '_onNeonAnimationFinish'
 },

I have tried using a property like the following but the _onNeonAnimationFinish callback is never fired.

class MyElement {
    get behaviors() {
        return [Polymer.NeonAnimationRunnerBehavior];
    }

    beforeRegister() {
        this.is = 'my-element';
        this.properties = {
            name: {
                type: String
            }
        };

        this.listeners = {
            'neon-animation-finish': '_onNeonAnimationFinish'
        };
    }

So what is the correct way?

like image 388
Jessica Avatar asked Dec 01 '15 12:12

Jessica


1 Answers

Following element code should work. Look at the comments in the code for explanation.

<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/neon-animation/neon-animation-runner-behavior.html">
<link rel="import" href="bower_components/neon-animation/animations/scale-down-animation.html">

<dom-module id="my-animatable">

  <style>
    :host {
      display: inline-block;
      border-radius: 50%;
      width: 300px;
      height: 300px;
      background: orange;
    }
  </style>

  <template>
    <content></content>
  </template>

</dom-module>

<script>
  (function() {
    'use strict';

    var behaviors = Symbol('behaviors');

    class MyAnimatable {
      get behaviors() {
        if (!this[behaviors]) {
          this[behaviors] = [Polymer.NeonAnimationRunnerBehavior];
        }

        return this[behaviors];
      }

      //this setter is key to solving this bug. The `NeonAnimationRunnerBehavior`
      //is an array with two behaviors in it. Polymer allows a
      //behavior to be an array or an object, because of this it flattens
      //nested behaviors into a single array containing only objects and
      //sets it on the prototype, since your implementation didn't have a
      //setter the flattened behavior was lost!.
      set behaviors(value) {
        this[behaviors] = value;
      }

      beforeRegister() {
        this.is = 'my-animatable';

        this.properties = {
          animationConfig: {
            type: Object,
            value: function() {
              return {
                name: 'scale-down-animation',
                node: this
              }
            }
          }
        };

        this.listeners = {
          'neon-animation-finish': '_onNeonAnimationFinish'
        };
      }

      animate() {
        this.playAnimation();
      }

      _onNeonAnimationFinish() {
        alert('_onNeonAnimationFinish');
      }
    }

    Polymer(MyAnimatable);
  })();
</script>
like image 194
Ajinkya Avatar answered Oct 28 '22 19:10

Ajinkya