6

... and callback method?

input_element.addEventListener("paste", self.hide, false);
input_element.addEventListener("keypress", self.hide, false);
input_element.addEventListener("drop", self.hide, false);

to a form similar to this -

input_element.addEventListener("paste keypress drop", self.hide, false);

I checked MDN and the API does not support this form but is there perhaps another way?

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • 1
    Store the function once in a variable before binding the events, then pass a reference to it to all the `addEventListener` calls. That doesn't accomplish you wanting to pass multiple event types to one `addEventListener` call, but it removes the need for multiple anonymous functions doing the same thing – Ian Jun 09 '14 at 18:24
  • It's possible to accomplish this using jQuery, incase you're interested in introducing libraries. – ArrayKnight Jun 09 '14 at 18:25
  • No you can't, it's that simple. You can however pass a named function. – adeneo Jun 09 '14 at 18:25
  • Write your own function, e.g. http://stackoverflow.com/a/8797106/961695 – Yuriy Galanter Jun 09 '14 at 18:25
  • @adeno - are you saying the form I provided will work? –  Jun 09 '14 at 18:27
  • No, I'm saying you can't pass more than one event at the time, but you can use the same function for all of them, but you still have to call addEventListener for each event. – adeneo Jun 09 '14 at 18:27
  • You can of course create all sorts of convience functions, like this one -> **http://jsfiddle.net/7HBnh/** – adeneo Jun 09 '14 at 18:30
  • @Yuriy - yep, I like splitting on the space character wrather than white space like Backbone does with its custom events. –  Jun 09 '14 at 18:30
  • @adeno - The link Yuriy provided has a better form, but both will work. What is the jQuery solution? –  Jun 09 '14 at 18:32
  • http://api.jquery.com/on/ is the jQuery solution –  Jun 09 '14 at 18:34

2 Answers2

4

Few years later, I don't see what's the difference between the example in the question and what I've written, so here is an update

["paste", "keypress", "drop"].forEach(event => input_element.addEventListener(event, self.hide, false));

ORIGINAL ANSWER

First thing that came to mind

function hide(){
    self.hide();
}

input_element.addEventListener("paste", hide, false);
input_element.addEventListener("keypress", hide, false);
input_element.addEventListener("drop", hide, false);
php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
1

The obvious DRY point is to declare the function once:

var updateFn = function () {
    self.hide()
};
input_element.addEventListener("paste", updateFn, false);
input_element.addEventListener("keypress", updateFn, false);
input_element.addEventListener("drop", updateFn, false);

There are other ways of doing it, but they probably aren't very sensible for you.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318