Skip to content

Instantly share code, notes, and snippets.

@kodi
Created March 31, 2011 22:20
Show Gist options
  • Save kodi/897382 to your computer and use it in GitHub Desktop.
Save kodi/897382 to your computer and use it in GitHub Desktop.
javascript & jquery multiple event listeners
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#button').click(function() {
FOO.trigger('buttonPushed', {bar:32});
});
});
</script>
<script type="text/javascript">
//let FOO be our namespace
var FOO = function() {
var BASE_EVENT_NAMESPACE = 'foo.event';
return{
registerEvent: function(eventName, handler) {
var _eventName = BASE_EVENT_NAMESPACE + '.' + eventName;
console.log("REGISTERING EVENT: " + _eventName);
$(this).bind(_eventName, handler);
},
trigger: function(eventName, extraData) {
var _eventName = BASE_EVENT_NAMESPACE + '.' + eventName;
console.log("TRIGGERING EVENT " + _eventName);
$(this).trigger(_eventName, extraData);
}
}
}();
//FOO app
FOO.app = function() {
return {
init:function() {
FOO.registerEvent('buttonPushed', this.handler);
},
handler:function() {
console.log("this is a event handler from the FOO.app");
}
}
}();
//FOO app - module Bar
FOO.app.moduleBar = function() {
return {
init:function() {
FOO.registerEvent('buttonPushed', this.handler);
},
handler:function(event, data) {
console.log("this is a event handler from FOO.app.moduleBar, printing data: ");
console.log(data);
}
}
}();
FOO.app.init();
FOO.app.moduleBar.init();
</script>
</head>
<body>
<input id="button" type="button" value="push me"/>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment