Polymer 将变量从元素传递到另一页上的事件侦听器

Polymer Pass Variables from Element to Event Listener on another page

从 Polymer Starter Kit 原型中,我有一个来自 <my-view1> 的函数,它通过事件侦听器从 <my-app> 触发一个函数。

我希望能够随之发送一些信息,所以我设置了一个数据属性,该属性被捕获在一个变量中。

然后如何将该变量发送到我的主事件侦听器并在 <my-app> 中运行?

<my-view1> 数据属性:

<paper-button raised on-tap="open" data-target="#dialog">Dialog</paper-button>

<my-view1> 函数:

open: function(e) {
  const target = e.target.dataset.target || e.target.parentElement.dataset.target;
  this.fire('open-dialog'); //send target variable somehow?
}

<my-app>听众:

listeners: {
  'open-dialog': 'handleOpenDialog' //get target variable from my-view1
}

<my-app>函数:

handleOpenDialog: function(e) {
  console.log(target); //get target variable from listener
}

谢谢!

您可以在调用 fire(eventName, [detail], [options]) 时指定事件详细信息。在您的情况下,您将在事件详细信息中传递 target(目标对话框的选择器),并且您的事件处理程序将使用该选择器查询其子项以获取对话框。

// my-view1
open: function(e) {
  const target = e.target.dataset.target;
  this.fire('open-dialog', target);
}

// my-app
handleOpenDialog: function(e) {
  const target = e.detail;
  const dialog = this.$$(target);
  if (dialog) {
    dialog.opened = true;
  }
}

HTMLImports.whenReady(() => {
  Polymer({
    is: 'my-app',

    listeners: {
      'open-dialog': 'handleOpenDialog'
    },
    
    handleOpenDialog: function(e) {
      const target = e.detail;
      const dialog = this.$$(target);
      if (dialog) {
        dialog.opened = true;
      }
    }
  });
  
  Polymer({
    is: 'my-view1',
    open: function(e) {
      const target = e.target.dataset.target;
      this.fire('open-dialog', target);
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.7.0/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link rel="import" href="paper-button/paper-button.html">
  <link rel="import" href="paper-dialog/paper-dialog.html">
</head>
<body>
  <my-app>
    <my-view1></my-view1>
  </my-app>

  <dom-module id="my-app">
    <template>
      <content></content>
      <paper-dialog id="dialog1">
        <h2>Dialog 1</h2>
        <div class="buttons">
          <paper-button dialog-dismiss>Cancel</paper-button>
          <paper-button dialog-confirm autofocus>Accept</paper-button>
        </div>
      </paper-dialog>
      
      <paper-dialog id="dialog2">
        <h2>Dialog 2</h2>
        <div class="buttons">
          <paper-button dialog-dismiss>Cancel</paper-button>
          <paper-button dialog-confirm autofocus>Accept</paper-button>
        </div>
      </paper-dialog>
    </template>
  </dom-module>

  <dom-module id="my-view1">
    <template>
      <paper-button on-tap="open" data-target="#dialog1">Dialog 1</paper-button>
      <paper-button on-tap="open" data-target="#dialog2">Dialog 2</paper-button>
    </template>
  </dom-module>
</body>

codepen