Create a custom event for a Polymer Custom-Element

3k views Asked by At

I've been trying to create an event to be triggered given certain conditional (more general case), but I have not found a way, at least not in the official documentation of Polymer for handling events

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

The custom element listen to another event, so he expects a condition is met to throw the internal event.

This is a little descriptive example:

Index.html

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

This code describes who will be listening to the event (myCustomEvent) and an action is detonated.


The other hand comes the implementation of the custom element

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

My problem is to fire the event when the condition is done, And listen that event outside (in index.html)

References

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

There are 1 answers

2
Scott Miles On BEST ANSWER

Try this. (Note: changed event names to be case-insensitive ['AnotherEvent' -> 'another-event'] because the HTML is happier this way):

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