为Polymer Custom-Element创建自定义事件

ljo*_*fre 1 javascript javascript-events polymer

我一直试图创建一个事件,在某些条件下(更一般情况下)被触发,但我没有找到办法,至少在Polymer的官方文档中没有找到处理事件的方法

https://www.polymer-project.org/0.5/articles/communication.html

自定义元素侦听另一个事件,因此他希望满足条件以抛出内部事件.

这是一个小描述性的例子:

的index.html

...
<my-element></my-element>
...
<script>
     var ele = document.querySelector("my-element");
     ele.addEventListener("myCustomEvent",
                 function(){
                     // some action
                     ...
             })
</script>
Run Code Online (Sandbox Code Playgroud)

此代码描述了谁将监听事件("myCustomEvent")并引爆了一个动作.


另一方面是自定义元素的实现

<polymer-element name="my-element">
  <template>
      <other-custom-element id="foo"></other-custom-element>
  </template>
  <script>
   Polymer("my-element", {
        ready: function(){
        var foo = this.$.foo;
        foo.addEventListener("AnotherEvent" , function(){
            ...
            if(condition){
                ...
                // in this part I need to fire the event 
                // "myCustomEvent"
            }
        })
        }
    })
  </script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)

我的问题是在条件完成时触发事件,并在外面侦听该事件(在index.html中)

参考

  1. https://www.polymer-project.org/0.5/articles/communication.html
  2. https://www.polymer-project.org/0.5/docs/polymer/polymer.html#fire

Sco*_*les 7

试试这个.(注意:更改的事件名称不区分大小写['AnotherEvent' - >'another-event']因为HTML更快乐):

<polymer-element name="my-element">
  <template>
      <other-custom-element on-another-event="{{doAnotherEvent}}"></other-custom-element>
  </template>
  <script>
   Polymer("my-element", {
      doAnotherEvent: function(){
        if (condition){
          // in this part I need to fire the event 
          // "my-custom-event"
          this.fire('my-custom-event');
        }
      }
    });
  </script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)

  • 在1.0中:使用`dom-module`而不是`polymer-element`,使用`on-another-event ="doAnotherEvent"`(没有花括号),并使用`Polymer({is:'my-element',. ..)`而不是`Polymer('my-element',{...`. (2认同)