2015-12-01 64 views
9

我基本上想以ES6的方式編寫下面的代碼。如何在Polymer中的ES6中編寫監聽器?

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

我已經使用如下但_onNeonAnimationFinish回調從來沒有發射的屬性嘗試。

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

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

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

那麼正確的方法是什麼?

+0

我不知道這是否正常工作或沒有,但你嘗試過做類似的行爲,並定義一個get聽衆(){回報{」 ...‘:’...}} – akc42

+1

我試着那也是一樣的結果。 :( – Jessica

+0

我也會這樣做的...... –

回答

2

以下元素代碼應該工作。查看代碼中的註釋以獲得解釋。

<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> 
+0

謝謝,這就是它! – Jessica