聚合物在另一页上从元素到事件侦听器传递变量

时间:2016-10-20 01:54:25

标签: polymer polymer-1.0

在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
}

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在调用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;
  }
}

&#13;
&#13;
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);
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

codepen