Set same click for multiple jQuery objects with CoffeeScript
I'm rolling my own modal with an overlay based on a Jack Moore article. I've been working it out using CoffeeScript instead of straight JS. I'm going to have the overlay click do the same thing as the close button click and I'm looking for an elegant DRY approach.
I've seen how multiple jQuery objects can share the same click using .add and I used that approach in the CoffeeScript to do that same thing and it works, but I'm wondering if there is a better or more correct way to do it?
# close the modal if you click the close button or overlay
$overlay.add($close).click (event) =>
event.preventDefault()
@closeModal()
I thought I saw something that listed the objects separated with commas and then .click() was attached, probably mixing things up that I've seen.
A comma is a multi-selector inside a selector string so you can say
$('#this, .that')
to combine multiple selectors in a selector string. So these have the same effect:
$a = $('#this').add($('.that'))
$b = $('#this, .that')
But you don't have selector strings, you already have the jQuery objects you're interested in so add
is the way to go.