Polymer 1.0 - 绑定一个事件处理程序而无需制作自定义元素

Polymer 1.0- bind a event handler without having to make a custom element

我在 index.html 中有 <div id="play-button-png" on-click="open-video"></div>。在不制作自定义元素的情况下,如何为其制作事件侦听器并将其绑定到单独的文件中?类似于 Angular 的控制器,您可以在其中绑定元素而无需创建指令。

您将使用“dom-bind”模板(也称为 'auto binding template')https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-bind

<template is="dom-bind" id="app">
  //document body
  <div id="play-button-png" on-click="openVideo"></div>
</template>

然后将函数添加到该模板范围

var app = document.querySelector('#app');
app.openVideo = function () {
  // do something when clicked
};

编辑:有时您需要等待模板绑定后才能进行任何操作。然后你会等待 'dom-change' 事件

app.addEventListener('dom-change', function() {
  // auto-binding template is ready.
});

这里还有另一种解释方法https://www.polymer-project.org/1.0/docs/devguide/events

事件侦听器设置

<dom-module id="x-custom">
  <template>
    <div>I will respond</div>
    <div>to a tap on</div>
    <div>any of my children!</div>
    <div id="special">I am special!</div>
  </template>

  <script>
    Polymer({

      is: 'x-custom',

      listeners: {
        'tap': 'regularTap',
        'special.tap': 'specialTap'
      },

      regularTap: function(e) {
        alert("Thank you for tapping");
      },

      specialTap: function(e) {
        alert("It was special tapping");
      }

    });
  </script>
</dom-module>

带注释的事件侦听器设置

<dom-module id="x-custom">
  <template>
    <button on-tap="handleTap">Kick Me</button>
  </template>
  <script>
    Polymer({
      is: 'x-custom',
      handleTap: function() {
        alert('Ow!');
      }
    });
  </script>
</dom-module>