문제

I have a classed button that I want to be able to put anywhere on my site and have jQuery attach an event handler to it. Since some of these buttons may be added to the DOM after initial page load, I need to scope the event handler to a parent selector, and listen for my classed button within the parent's scope.

Example (in CoffeeScript):

@$body = $('body')    
@$body.on 'click', '.pay-button', @handlePayButton

handlePayButton: (e) =>
  /* Do something */

This is obviously not terribly efficient, as it needs to listen to every click within @$body, so it would be much better to scope it to something more specific:

@$contentPage = $('#content-page')    
@$contentPage.on 'click', '.pay-button', @handlePayButton

handlePayButton: (e) =>
  /* Do something */

However, I want to be able to use this classed button in a modal window that would both be added to the DOM after the initial load, and also be outside of the scope of @$contentPage.

Is it more efficient to leave the scope at a lower specificity (ie: @$body), or to just simply have two scopes that are looking for this class:

@$contentPage = $('#content-page')
@$modal = $('#modal')
@$contentPage.on 'click', '.pay-button', @handlePayButton
@$modal.on 'click', '.pay-button', @handlePayButton

handlePayButton: (e) =>
  /* Do something */

Or alternatively, does it make sense to just add a new listener within the modal initializer that adds an event handler directly to $('.pay-button')?

도움이 되었습니까?

해결책

I would attach the handler for the modal after the modal initializes to the modal itself, and you can just attach it as

$('#modal .targetClass');

For the rest of the buttons, I guess the highest containing parent would do. On a current project I am working on, we have a div that contains all the body content excluding header and footer. It is what I use to attach misc classes that could appear anywhere within.

I think it's better to leave the modal on its own because sometimes modal are an immediate child of the body and therefore you would need to target the entire body to include the modal. Also the modal might not be used all that often so I think attaching something to the body for a modal that might not come up every time is a waste.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top