Reputation:
I know this is a duplicate topic, but this topic is different because i use very simple examples. I have a JavaScript function like this:
(function myfunction($){
function a(){
alert("A section");
}
function b(){
alert("B section")
}
})();
I want to create a HTML button which calls function A, and function B. How can i do that?
Upvotes: 0
Views: 98
Reputation: 1706
You can create a variable first, and then expose it to global context:
(function myfunction($){
var global = {
a: function(){
alert("A section");
},
b: function(){
alert("B section")
}
};
window.global = global;
})();
global.a();
global.b();
Upvotes: 0
Reputation: 5438
You can create an object that has these function and call your functions like below :
myFunctions = {
a : function(){ alert("A section"); },
b : function(){ alert("B section"); }
}
and then call them like below :
myFunctions.a();
myFunctions.b();
This is the jsfiddle to check it.
UPDATE:
As answer to your comment, this is an updated jsfiddle to show you how it works from HTML.
Upvotes: 1
Reputation: 1312
Assign function to global variables in closure is one way. Other way to do it is following.
(function myfunction($){
$("#button1").click(function {
alert("A section");
});
$("#button2").click(function {
alert("B section");
});
})(jQuery);
This doesn't spoil your global scope. And binds on click event for your buttons.
When not using jQuery
(function myfunction($){
var button1 = getElementById("idOfButton1");
button1.onclick = function {
alert("A section");
};
var button2 = getElementById("idOfButton2");
button1.onclick = function {
alert("B section");
};
})();
Upvotes: 0
Reputation: 781370
Make them global by declaring the names outside the closure, then assign them within the closure.
var a, b;
(function myfunction($){
a = function() {
alert("A section");
}
b = function() {
alert("B section")
}
})();
You can reduce the pollution of the global namespace by wrapping them in an object:
var myfuns = (function myfunction($) {
return { a: function() {alert("A section");},
b: function() {alert("B section");}
};
})();
Then call myfuns.a
and myfuns.b
.
Upvotes: 2