How can I trigger an event on an element in Polymer?

How it works without Polymer

In JavaScript, you can trigger an event by simply calling a method on the element itself:

<input id="foo" type="text" onclick="console.log('Click event triggered');" /> 
 var elem = document.getElementById('foo'); elem.onclick(); 

This works great, as shown in this JSFiddle demo .

Trying to do the same in Polymer

The polymer, however, has a different syntax and uses on-click instead of onclick :

 <input type="text" on-click="{{ clickEvent }}" /> 
 Polymer('my-element', { clickEvent: function() { console.log('Click event triggered.'); } }); 

I want to manually trigger the on-click event in the input element every time I press a key. To do this, I use the on-keypress , which fires the doClick event:

 <input type="text" on-click="{{ clickEvent }}" on-keypress="{{ doClick }}" /> 
 doClick: function(event, detail, sender) { console.log('Keypress event triggered.'); sender.onclick(); } 

In accordance with the binding to Polymer sender events, here is the element in which the event occurred ( input element in this case). This, unfortunately, gives me the following result:

Keypress event pressed
Uncaught TypeError: object is not a function

The error occurs because sender.onclick is null , as you can see (only in Chrome) in this JSFiddle * demo .

How can I trigger an event on an element in Polymer?

* I tweaked the Polymer setup from another JSFiddle demo. This for some reason only works in Chrome, however this problem is not specific to Chrome itself.


Before someone asks me why on earth I would like to trigger a click event on the input element every time I press a key, note that this is nothing more than a really crude example, and not the actual code I'm using. This was the shortest path I could demonstrate.

+5
source share
2 answers

The correct way to fire the click event is calling click() instead of onclick() , so the correct function will be

 doClick: function(event, detail, sender) { console.log('Keypress event triggered'); sender.click(); } 

here is the jsfiddle demo

You can also call a function instead of triggering an event if you specify the same element

 Polymer('my-element', { clickEvent: function() { console.log('Click event triggered'); }, doClick: function(event, detail, sender) { console.log('Keypress event triggered'); this.clickEvent(); } }); 

here is another jsfiddle demo

+4
source

Summary of comments on @scottMiles:

A more general way to trigger events is through the dispatchEvent DOM api or a helper method on polymer elements called fire . - Scott Miles

+1
source

Source: https://habr.com/ru/post/1200991/


All Articles