newcasio
newcasio

Reputation: 253

Passing a parameter into an event handler

I would like to use this event handler to run a function passing in these parameters.

$('#checkingDeposit').on('click', { amount: 100, account: 'savings' }, bank.deposit);


deposit: function(event, amount, account) {
  console.log('deposit running');
  console.log(event.data);   //object of key value pairs
  console.log(event.data.account);    //output 'savings'
  console.log(event.data.amount); //output 100
  this[event.data.account] += event.data.amount;
  console.log(this[event.data.account]);  //NaN
  return this[event.data.account];
}

Am i getting a NaN when i try to console.log this[event.data.account] because i am trying to pass a string (ie 'savings') to the this object?

Thanks in advance Brad

Upvotes: 1

Views: 171

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

You must pass a function or a function reference to an event binding expression so if you need to pass arguments, you can wrap the actual function call (with parameters) in an anonymous function and pass that to the event binding expression.

let bank = {
  deposit:50
};

$('#checkingDeposit').on('click', function(event) {
  deposit(event, {amount:100, account:'savings'}, bank.deposit)
});
    
    
function deposit(event, obj, account){
  console.log('deposit running');
  console.log(obj.account);    //output 'savings'
  console.log(obj.amount); //output 100
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="checkingDeposit">Deposit</button>

Upvotes: 1

Related Questions