聚合物1.0中的委托处理程序

Handlers delegation in polymer 1.0

本文关键字:处理 程序 聚合物      更新时间:2023-09-26

UPDATE:响应和错误事件不再是气泡。https://github.com/PolymerElements/iron-ajax/releases/tag/v1.0.5真遗憾。

原始问题:

我想创建一个基于iron-ajax的自定义ajax组件,添加几个自定义的头和处理程序。虽然还没有实现自定义元素继承,但我只是将iron ajax添加到了我的ajax中,并将所有api委托给iron ajax,这在generateRequest中运行良好。

但当涉及到处理程序方法时,我注意到它在没有任何委托的情况下工作。在我的ajax elt中没有定义响应处理程序,但handleResponse仍然被调用。

据我所知,之所以会发生这种情况,是因为Polymer.Base_addFeature_createEventHandler(Polymer.html:345)使用顶级elt的"this"作为处理程序方法定义的"host"。

所以问题是:是bug还是特性?

示例代码:

<link rel="import" href="https://raw.githubusercontent.com/Polymer/polymer/master/polymer.html">
<link rel="import" href="https://raw.githubusercontent.com/PolymerElements/iron-ajax/master/iron-ajax.html">
<dom-module id="my-ajax">
    <template>
         <iron-ajax
                id="ironAjax"
                url="http://echo.jsontest.com/key/value/otherkey/othervalue"
                handle-as="json"
                debounce-duration="300"
                >
        </iron-ajax>
    </template>
  <script>
    Polymer({
        is: "my-ajax",
      
        generateRequest: function(){
             this.$.ironAjax.generateRequest();
        }
    });
</script>
</dom-module>
<dom-module id="my-elt">
  <template>
    <button on-click="buttonClick">Button</button>
    <my-ajax
              id="myAjax" 
              on-response="handleResponse">
        </my-ajax>
  </template>
  <script>
    Polymer({
        is: "my-elt",
        buttonClick: function(){
          this.$.myAjax.generateRequest();
        },
        handleResponse: function(event) {
          alert('got response');
        }
    });
</script>
</dom-module>
<my-elt></my-elt>

大多数事件都是冒泡的,所以您只是通过放置在my-ajax实例上的处理程序看到response事件从my-ajax冒泡到my-elt作用域。这与click事件从较低范围冒泡到较高范围的情况相同。

所以答案是:"特性"(网络平台,比聚合物本身更重要)。