I need to access some variables from within a 'listener' of sorts (for Facebox) in my javascript. How do I communicate variables between javascript functions and event listeners?
I have been messing about a bit with scope, but it seems that declaring global variables is a bit hacky, especially once you start factoring in other controls (ie. pagination for my results within the modal) that wouldn't sit so well as global variables.
This is the section that is causing me problems:
function song_clarify ()
{
// th开发者_开发技巧is launches a modal window, fills with html.
$.facebox('<div id="search"><div></div></div>');
}
// AJAX function. when called, this loads the required htmls into the modal
function clarify_loader()
{
var loadUrl = "ajax/clarify";
$("#search > div")
.html(ajax_load)
.load(loadUrl, 'search='+source+'&searchTerm='+song);
}
// Waits for the modal to be revealed before calling AJAX function.
// (if function called outside listener, nothing for the AJAX to bind to as modal appears dynamically)
$(document).bind('reveal.facebox', function() {
// Problem is here. Need to be able to do clarify_loader(source,song)
clarify_loader();
})
In the example you have used, a var outside of the the $(document).bind('reveal.facebox', function() {}) would be the correct design. This link might help:
http://api.jquery.com/bind/
Go to the section called "Passing Event Data"
Well, you did not provide from where source and song variables are declared. If they are coming from an input filled by a user then I believe you'd have no problem. If you're assigning the value within clarify_loader then just use global variables
var var1, var2;
function a(){
var1 = "x"
var2 = "y"
}
function b(){
alert(var1) //x
alert(var2) //y
}
and then when you call functions a and b respectively your variables will have the value x and y.
精彩评论