dman
dman

Reputation: 11064

Polymer 1.0- bind a event handler without having to make a custom element

I have <div id="play-button-png" on-click="open-video"></div> in the index.html. Without making a custom element, how can I make the event listener for it and bind it in a separate file? Similar to Angular's controller, where you can bind a element without having to create a directive.

Upvotes: 2

Views: 916

Answers (2)

tiomno
tiomno

Reputation: 2228

There is another way explained here https://www.polymer-project.org/1.0/docs/devguide/events

Event listener setup

<dom-module id="x-custom">
  <template>
    <div>I will respond</div>
    <div>to a tap on</div>
    <div>any of my children!</div>
    <div id="special">I am special!</div>
  </template>

  <script>
    Polymer({

      is: 'x-custom',

      listeners: {
        'tap': 'regularTap',
        'special.tap': 'specialTap'
      },

      regularTap: function(e) {
        alert("Thank you for tapping");
      },

      specialTap: function(e) {
        alert("It was special tapping");
      }

    });
  </script>
</dom-module>

Annotated event listener setup

<dom-module id="x-custom">
  <template>
    <button on-tap="handleTap">Kick Me</button>
  </template>
  <script>
    Polymer({
      is: 'x-custom',
      handleTap: function() {
        alert('Ow!');
      }
    });
  </script>
</dom-module>

Upvotes: 1

jimi dough10
jimi dough10

Reputation: 2016

you would use the 'dom-bind'template (also known as 'auto binding template') https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-bind

<template is="dom-bind" id="app">
  //document body
  <div id="play-button-png" on-click="openVideo"></div>
</template>

then add the function to that templates scope

var app = document.querySelector('#app');
app.openVideo = function () {
  // do something when clicked
};

edit: sometimes you will need to wait for the template to be bound before manipulating anything. you would then wait for the 'dom-change' event

app.addEventListener('dom-change', function() {
  // auto-binding template is ready.
});

Upvotes: 4

Related Questions