Last active
December 21, 2015 15:19
-
-
Save nmoliveira/6325428 to your computer and use it in GitHub Desktop.
jQuery Custom Events - one event but more than one handler to be executed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>jQuery Custum Events</title> | |
<script src="jquery.js"></script> | |
<style type="text/css"> | |
#messages{ | |
width: 200px; | |
height: 100px; | |
border: 1px solid #000000 | |
} | |
</style> | |
</head> | |
<body> | |
<input type="button" id="btnSayHello" value="Say Hello"> | |
<div id="messages"></div> | |
<script type="text/javascript"> | |
/* | |
On the click of the button, an alert will be shown | |
and we a jquery custom event will be trigger (answer) | |
This event has 2 handlers (Iam and whoAreYou) that will | |
show 2 messages on the div. | |
*/ | |
$(function(){ | |
// wrap div with jquery | |
var $messages = $('#messages'); | |
// on button click | |
$('#btnSayHello').on('click', function() { | |
alert('Hello, anybody there?'); | |
// trigger custom event | |
$messages.trigger('answer'); | |
}); | |
// first handler | |
var Iam = function(){ | |
$messages.append('I am! <br />'); | |
}; | |
// second handler | |
var whoAreYou = function(){ | |
$messages.append('Who are you?'); | |
} | |
// bind custom event | |
$messages.on('answer.Iam', Iam); | |
$messages.on('answer.whoAreYou', whoAreYou); | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment