Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 invoking the 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 fine, as can be seen in this JSFiddle demo.

Attempting to do the same in Polymer

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 call the on-click event on my input element every time a key is pressed. For this I'm using an on-keypress handler which fires my doClick event:

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

As per Polymer's event binding, sender here is the element which the event occurred on (my input element in this case). This unfortunately gives me the following output:

Keypress event triggered
Uncaught TypeError: object is not a function

The error happens because sender.onclick is null, as can be seen (on Chrome only) in this JSFiddle demo*.

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

* I've pinched the Polymer set-up from someone else's JSFiddle demo. This for whatever reason is only working in Chrome, however this problem isn't specific to Chrome itself.


Before anyone asks me why on earth I'd want to trigger the click event on an input element every time a key is pressed, do note that this is nothing more than really crude example and not the actual code I'm using. This was just the shortest way I was able to demonstrate the problem.

like image 214
James Donnelly Avatar asked Aug 23 '14 20:08

James Donnelly


1 Answers

The correct way to trigger a click event is calling click() instead of onclick(), so the correct function would be

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

here is the JSFiddle Demo

You can also call the function instead of triggering an event if you are pointing 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

like image 127
OmarCastro Avatar answered Sep 27 '22 18:09

OmarCastro