I have a jQuery function which accepts few arguments based on the argument I should call another jQuery function.
example:
arg0 = "Launch"
arg1 = "menu"
example:
(function($)
{
preRender: function(arg0,arg1)
{
var nextFuncName = arg0+arg1; //launchmenu
nextFuncName() // hope to call the function name framed from the number of arguments
}
})(jQuery);
(function($)
{
launchmenu: function()
{
console.log("Launchmenu called");
}
})(jQuery);
I referred the following link calling a jQuery function named in a variable but I don't want to use eval() or window object.
Is it possible to use $.proxy or any other method to achieve this functionality, also is it possible to achieve this using underscore.js?
Any help will be appreciated.
1 Answer 1
Try utilizing jQuery object
...or much better an own, local object, instead of polluting the global jQuery namespace.
Merge them so that you use
localObjectforlaunchmenubut$forpreRender
(function($) {
var localObject = {};
function launchmenu() {
console.log("Launchmenu called")
}
function preRender(arg0, arg1) {
var nextFuncName = arg0 + arg1;
if (nextFuncName in localObject) {
localObject[nextFuncName]()
} else {
console.log(typeof nextFuncName)
}
}
localObject.launchmenu = launchmenu;
$.preRender = preRender;
}(jQuery));
$(function() {
$.preRender("launch", "menu");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
5 Comments
preRender to $, only all those dynamically-named function should stay inside the IIFE.$ within if condition to this , so call, apply could be utilized ; without redefining $ before, when called. Not certain interpreting "only all those dynamically-named function should stay inside the IIFE." portion correctly ? Can describe details ?localObject for launchmenu but $ for preRender .Explore related questions
See similar questions with these tags.
myObject. Then you can writemyObject[arg0 + arg1]().