简体   繁体   中英

Best practice for passing arguments to an event handler function

Suppose I have a button (several buttons actually) that when clicked will do 1 of 2 things. Which of those 2 things depends on an argument passed to the function. This will be used all over so I need to put in a function... as opposed to having the code execute in an anonymous function each time. I'm using jquery and wondering what the best way is to feed the click-handler function a parameter and value. Also, I'd like to keep a reference to the button intact as $(this) if at all possible. here's what i've got:

$(document).ready(function() {
   $('#button1').click({ labelStr: 'Open File' }, doLabel);
   $('#button2').click({ labelStr: 'Close Window' }, doLabel);
});

function doLabel(e) {
  console.log('it is: %o', e.data.labelStr);
  $(this).html(e.data.labelStr);
}

...which works - jsfiddel - but I know there are many ways to skin this cat. What holes can be poked in this approach?

Your code looks fine to me. Are you looking for a way to pass arguments and have them map directly to the click handler's parameters list? If that's the case, you can try this:

$(document).ready(function() {
   $('#button1').click(function() {doLabel.call(this, "Open File");});
   $('#button2').click(function() {doLabel.call(this, "Close Window");});
});

function doLabel(labelStr) {
  console.log('it is: %o', labelStr);
  $(this).html(labelStr);
}

If there are multiple parameters, you can do doLabel.call(this, arg1, arg2, ...) .

Like DelightedD0D suggested, I would also use data attributes. You can use $(this) in your event handler to reference the element, and so avoid the anonymous functions.

 $(document).ready(function() { $('button').click(doLabel); }); function doLabel() { $(this).html($(this).data('label-str')); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <button data-label-str="Open File">Give me a label please</button> <p>&nbsp;</p> <button data-label-str="Close Window">Give ME a label TOO please</button> 

If I understand you correctly, I'd just add the string as a data attribute on the button and send this to the function. Let the function use this to get the string from the button

jsFiddle

 $(document).ready(function() { $('button').click(function(){doLabel(this)}); }); function doLabel(e) { $(e).html($(e).data('label-str')); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <button data-label-str="Open File">Give me a label please</button> <p>&nbsp;</p> <button data-label-str="Close Window">Give ME a label TOO please</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM