代码之家  ›  专栏  ›  技术社区  ›  Matthew

如何在聚合物中使用Javascript设置</paper button>的“点击”行为

  •  0
  • Matthew  · 技术社区  · 7 年前

    我想加一个 paper-button 用Poylmer中的函数在飞行中处理DOM2倍.

    我希望这个新按钮在点击时调用另一个函数。

    appendNodeToDom() {
      let prop = this.result[i]['someProperty'];
      let node = document.createElement("paper-button");
      let button = document.createTextNode(prop);
    
      button.ontap = this.go(); // what is the proper syntax for this?
    
      node.appendChild(button);
      this.shadowRoot.getElementById('buttons').appendChild(node);
    }
    
    go() {
      console.log('go');
    }
    

    button.addEventListener("click", this.go());
    button.addEventListener("tap", this.go());
    

    如何在聚合物中使用Javascript设置“on-tap”行为2倍?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Umbo    7 年前

    问题是你在打电话 button 文本节点 里面 paper-button 并在该节点上设置事件侦听器 Text 节点-不触发事件(除了一些 exceptions

    而且,你也通过了 this.go() 作为回拨 addEventListener . 这意味着 这个。走() 被执行 然后返回值作为回调传递(在本例中 undefined 因为在console.log之后,您不会返回任何内容)。您应该传递函数的标识符而不调用它:

    addEventListener('tap', this.go);
    

    appendNodeToDom() {
      let prop = this.result[i]['someProperty'];
      let button = document.createElement('paper-button');
      let text = document.createTextNode(prop);
    
      button.appendChild(text);
      button.addEventListener('tap', this.go); // Add the listener to button
      this.shadowRoot.getElementById('buttons').appendChild(node);
    }
    
    go() {
      console.log('go');
    }
    

    请注意:请记住,Polymer有很多工具可以避免执行直接的DOM操作。如果你只需要在列表中添加一个按钮,你可以考虑一个解决方案 dom-repeat