Reputation: 47595
This is how I wrap all my JavaScript:
;(function($, window, undefined) {
var document = window.document;
var myFunction = function() {}
})(jQuery, window);
But now I have the need to call myFunction from outside of that closure.
window.addEventListener("offline", function(e) {
myFunction();
}, false);
Q: How do I name the self executing anonymous function so that I can call myFunction from the global scope?
Upvotes: 0
Views: 85
Reputation: 15104
Assign the function to a property of whichever object/scope you want to use.
;(function($, window, undefined) {
var document = window.document;
var myFunction = function() {};
window.myFunction = myFunction;
})(jQuery, window);
You'd preferably want to return something from your IIFE that encapsulates all your 'exports' though.
var exports = (function($, window, undefined) {
var document = window.document;
var myFunction = function() {};
return {
"myFunction": myFunction
};
})(jQuery, window);
window.addEventListener("offline", function(e) {
exports.myFunction();
}, false);
AMD is helpful for this style of programming.
Upvotes: 2
Reputation: 72697
Pretty easy, just attach your function to the global object (window):
;(function($, window, undefined) {
var document = window.document;
var myFunction = function() {}
window.myNamedFunction = myFunction;
})(jQuery, window);
Upvotes: 2
Reputation: 207491
Use a namespace and push that to the global scope.
window.yourNamespace = window.yourNamespace || {};
window.yourNamespace.myFunction = function() {};
Upvotes: 1