Reputation: 671
I have a main page that loads a child page via ajax, then when the child page is closed a globally scoped callback function is run to do whatever action is necessary, for example to refresh the main page content in some way.
I came across a situation where the child page itself needs to define the callback function since it is the only place that knows what needs to be done when it closes.
In this instance the callback function is a closure of another function that accepts parameters, and the parameters are derived from a jquery expression using elements on the child page.
The problem is by the time the callback function is run the child page has been unloaded so when the enclosed function's parameter list is evaluated jquery cannot locate the target elements.
I was able to work around this one case by using a globally scoped temporary variable to hold the parameter but I would rather 'force' evaluation of the jquery expression while the page is still in memory.
A pseudo-code example of the setup that does not work:
main-page:
callback = null;
newcallback = some_function;
function open-child(newcallback) {
callback = newcallback;
//load child page
};
function close-child(){
//unload child page
callback();
}
child-page:
child-page-element
callback = function () {
some_action( $("#child-page-element").data("id") );
};
close-child();
by adding a global variable I can make this work:
child-page:
child-page-element
global_var = $("#child-page-element").data("id");
callback = function () {
some_action(global_var);
};
close-child();
Questions:
Can the jquery param be 'forced' to evaluate as I have it written?
Is there a better way altogether?
Upvotes: 1
Views: 130
Reputation: 1165
Well, you could make a function on the child page that creates the callback (and gathers its data) like:
main-page:
function open-child(createCallback) {
callback = createCallback();
}
child-page:
createCallback = function() {
var id = $("#child-page-element").data("id");
return function () {
some_action(id);
};
};
Upvotes: 1