Here's an alternative, that boils down to <Element>.addEventListener(<eventName>, <function>.bind(<this>[,<arg1>][,<arg2>]));
bind
wraps the intended function, and performs a call on it using additional specified parameters (args). The first parameter of bind
will be the this
instance of the function. Setting it to undefined
will pass the original this
instance.
Short Answer (jQuery)
$(document).ready(function()
{
$("#popup1").hide();
$('.b-popup').on('click', function(targetId, e){
console.log("%o %o %o", targetId, e.target.id, e);
if( e.target.id !== targetId ){ return; }
PopUpHide();
}.bind(undefined, "popup1"));
});
function PopUpShow(){
$("#popup1").show();
}
function PopUpHide(){
$("#popup1").hide();
}
the fiddle: http://jsfiddle.net/p7NbX/1514/
Original Answer
The following sample is really more geared for reuse and oop (ish).
/* I'm going to declare and keep my initialization code in an object.
that I'll run when the document is ready.
*/
var MyHandlerManager =
{
'elms' : [],
'init': function()
{
var CssSelector = "div.b-popup";
var elms = document.querySelectorAll(CssSelector);
for (var i = 0; i < elms.length; i++)
{
elms[i].addEventListener('click', MyHandlers.HidePopupHandler.bind(undefined, elms[i].id));
}
/* you can skip this.
You don't need to keep a reference to elms (NodeList) for the EventListeners to function properly.
*/
MyHandlerManager.elms = elms;
}
};
You can do anonymous functions instead of referencing the existing functions as handlers, but I like to declare my handlers this way..
This bring some debugging and runtime considerations; like,
- clearing out the console.logs lines easier and/or,
- replacing the handler functions at some later point if need be necessary.
var MyHandlers =
{
"ShowPopupHandler": function (targetId, e)
{
console.log("targetId: %o :: e.target.id: %o :: EventArgs: %o", targetId, e.target.id, e);
if (e.target.id !== targetId) { return; }
var elm = document.getElementById(targetId);
elm.style.display = "block";
},
"HidePopupHandler": function (targetId, e)
{
console.log("targetId: %o :: e.target.id: %o :: EventArgs: %o", targetId, e.target.id, e);
if (e.target.id !== targetId) { return; }
var elm = document.getElementById(targetId);
elm.style.display = "none";
}
};
$(document).ready(function(){
PopUpHide();
MyHandlerManager.init();
/* Again, you could just take the code in the init() function
and run it here..
using 'bind' to wrap the intended function and call it, passing the elm.id as an argument (first arg) into anonymous functions.
*/
});
function PopUpShow(){
$("#popup1").show();
}
function PopUpHide(){
$("#popup1").hide();
}