JongHyeon Yeo
JongHyeon Yeo

Reputation: 1009

When using Javascript, Jquery with event handler, how could it be known 'event is event'?

Following codes work well. Whenever I click on an item, It opens or closes. But the event valuable has some strange behavior to a newbie.

enter image description here

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>event.target demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<ul>
  <li>item 1
    <ul>
      <li>sub item 1-a</li>
      <li>sub item 1-b</li>
    </ul>
  </li>
  <li>item 2
    <ul>
      <li>sub item 2-a</li>
      <li>sub item 2-b</li>
    </ul>
  </li>
</ul>

<script>
function handler( event ) {
  var target = $( event.target );
  if ( target.is( "li" ) ) {
    target.children().toggle();
  }
}
$( "ul" ).click( handler ).find( "ul" ).hide();
</script>

At the first time, I think event as a variable declared from "https://code.jquery.com/jquery-10.2.js"

So I changed the name of 'event' to 'xxx', and tested.

function handler( xxx) {
  var target = $( xxx.target );
  if ( target.is( "li" ) ) {
    target.children().toggle();
  }
}
$( "ul" ).click( handler ).find( "ul" ).hide();

But It also works well and makes no error.

Finally, I changed codes like this.

function handler( xxx ) {
  var target = $( xxx.target );
  var target2 = $( ppp.target );

  if ( target.is( "li" ) ) {
    target.children().toggle();
  }
}
$( "ul" ).click( handler ).find( "ul" ).hide();

But It makes Uncaught ReferenceError: ppp is not defined. So I'm wondering how and where the event or xxx variables come from. And I also want to know how javascript interpreter translate 'xxx' as a function which has target property.

Upvotes: 1

Views: 91

Answers (1)

t.niese
t.niese

Reputation: 40842

handler is a function that you pass as callback to other function.

This handler function has the parameter event, xxx or however you define it. The handler function is then at a later point called with some argument.

// this function will accept another function as argument
// this callback will then be called after 1 second, that function is called
// using an object as first argument
function callInOneSecond(callback) {
  setTimeout(function() {
    callback({
      traget: 'something'
    })
  }, 1000);
}


// it does not matter how the first parameter is called, it will always 
// hold the first argument that is passed to it when "handler" is called.
function handler(xxx) {
  console.log('was called');
  console.dir(xxx);
}

callInOneSecond(handler);

Upvotes: 1

Related Questions