Eckstein Eckstein - 5 months ago 6
Javascript Question

Correct syntax to convert my jQuery script to a reusable function

So I have a script structured like this:

$('.save-audition').on('click', function() {
STUFF HAPPENS HERE
})


It's working great. But, there are several elements besides .save-audition that I would like to use the same script with just a few variables different. By searching around, I thought the below would work, but it doesn't seem to do the trick. What's the correct syntax I should be using?

$('.save-audition').on('click', tps_save_listing(audition));
$('.save-job').on('click', tps_save_listing(job));

function tps_save_listing(type) {
STUFF HAPPENS HERE
}

Answer

You are calling function immediately at tps_save_listing(audition), tps_save_listing(job), instead of passing reference to tps_save_listing function. You can alternatively use event.data to pass variables to event handler tps_save_listing

$(".save-audition").on("click", null, audition, tps_save_listing);
$(".save-job").on("click", null, job, tps_save_listing);

function tps_save_listing(event) {
    // STUFF HAPPENS HERE
    console.log(event.data);
}

var audition = 123;
var job = "abc";
$(".save-audition").on("click", null, audition, tps_save_listing);
$(".save-job").on("click", null, job, tps_save_listing);

function tps_save_listing(event) {
  console.log(event.data)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="save-audition">
save audition
</div>

<div class="save-job">
save job
</div>

jsfiddle https://jsfiddle.net/p1gcxw5y/

Comments