聚合物-此对象在功能中不可用

Polymer- this object not available in function

使用 Polymer 1.0。我需要 setTimout,因为当我 运行 this.$$('google-youtube'); 时存在 <template is="dom-if" if="{{foo.bar}}"><google-youtube> 可用的竞争条件。为了保持代码干净,我喜欢将 startPlayer 播放器提取出来。但是 this 对象在 setTimeout(this.startPlayer, 1000); 调用时不可用。我怎样才能解决这个问题?由于这些功能是 Object.create() 的属性,因此不确定如何。

<script>
    Polymer({
      is: "video-player",
      behaviors: [ 
        Polymer.PaperDialogBehavior,
        Polymer.NeonAnimationRunnerBehavior
                 ],
      properties: {
        foo: Object,
        entryAnimation: {
          value: 'scale-up-animation'
        }
      },
      listeners: { 'iron-overlay-opened': 'enableElement',
                   'iron-overlay-closed': 'stopPlayer'
      },
      startPlayer: function() {
        youtubePlayer = this.$$('google-youtube');
        if (youtubePlayer.playbackstarted) {
         youtubePlayer.play();
        }
      },
      enableElement: function(e) {
        //this.playAnimation();
        this.foo = { bar: true};
        setTimeout(this.startPlayer, 1000);
      },
      stopPlayer: function(e) {
        youtubePlayer = this.$$('google-youtube');
        youtubePlayer.pause();
        youtubePlayer.seekTo(5);
      }
    });
  </script>

替换为:

setTimeout(this.startPlayer, 1000);

...有了这个:

setTimeout(this.startPlayer.bind(this), 1000);

如果您不熟悉 .bind() 的工作原理,这里是 MDN docs 的简要说明:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

请注意,.bind() 在 <=IE8 中不可用,但 polyfill 非常容易。如果您不喜欢 polyfilling(并且您需要 IE8 的支持),您也可以将该行代码替换为以下代码:

var self = this;
setTimeout(function() {
    self.startPlayer();
}, 1000);