Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Is placing event listeners inside a function bad?

Is placing event listeners inside a function bad? This is a sample of my work where I need to have a reference to the previously clicked button

$mapGuideBar.on("click", "li", function(){ mapGuideBarItemClicked(this); });

function mapGuideBarItemClicked(item) {

      $mapGuidePopupBtns.eq( btnsEnum.COLLAPSE ).on('click', function(){
           //do something based on value of item
    });

}

1 Answer

Steven Parker
Steven Parker
243,318 Points

It's not bad if it's really what you want to do. So here it seems you only want clicking on the "COLLAPSE" button to work after a click was made on a list item. If that's your intention, this should do it.

But you might also want to guard against attaching redundant handlers in case the same (or another) list item is clicked again.

Thank you for you reply Steven Parker . Regarding guarding against attaching redundant handlers, are you referring to something like this?

function someMethod()
{
  $(obj).off('click').on('click', function(e) {
    // put your logic in here 
  });
}
Steven Parker
Steven Parker
243,318 Points

Sure, that should do it. You could also establish both handlers just once, and use a shared variable to control what they do.