I am trying to take advantage of Javascript closures by creating a method in one context and storing it in a global variable so that it may be called later from another context.
//Global variable to hold the function
开发者_开发问答var revertEvent;
//creates the function and assigns it to the global variable
function createRevertFunction(eventToBeReverted) {
revertEvent = function () {
alert("Now Restoring Event");
$('#calendar').fullCalendar('renderEvent', eventToBeReverted, true);
}
}
So, the "createRevertFunction" holds the state of the original object. That object "eventToBeReverted" is modified down the road after this function is called, so this provides a means to restore the original to the UI without page refresh.
My problem is that I can't seem to call the function in the variable "revertEvent".
I've tried:
revertEvent();
revertEvent.call();
window[revertEvent]();
and none of them work. Any help would be appreciated...!
I think the most likely problem here is that you're attempting to call revertEvent
before it's been set via createRevertFunction
. To verify this change the declaration of revertEvent
as follows
var revertEvent = function() { alert('not set yet'); }
This will pop up the alert "not seet yet" in the case it's called before createRevertFunction
make createRevertFunction return the interior function. Assign.
var revertEvent;
//returns the function so we can do whatever with it
function createRevertFunction(eventToBeReverted) {
return function () {
alert("Now Restoring Event");
$('#calendar').fullCalendar('renderEvent', eventToBeReverted, true);
}
}
revertEvent = createRevertFunction(e);
>>> var revertEvent;
undefined
>>> (function() { revertEvent = function() { alert('hi') } })();
undefined
>>> revertEvent()
This works for me. Show us your usage of the function, createRevertFunction
...
revertEvent is defined only inside your function and is forgotten afterwards. You will have to save it to a global variable (that is defined outside the function) or rather return the created function and store it.
精彩评论