Just like in the PHP I need a variable variable.
I`m getting a data-type from the html and that variable is actually a function in the js code.
And I get it I need to call it.
Every time its different, so I don`t know which one exactly is.
if (e.which == 114 || e.which == 116) {
var action = $('.active').data("action");
action();
}
function testing() {
alert('yes');
}
Here the function name is testing.And the variable action is holding it.
How I`m suppose to call it ?!
I remember that there was a easy syntax for that,but I cant find it.
Thanks
You could extract the value and use eval().
<div id="something" data-action="alert('test')">SOME DIV</div>
$(document).ready(function() {
var $myObject = $("#something");
var action = $myObject.data('action');
$myObject.click(function() {
eval(action);
});
});
Try it yourself on jsfiddle
However, eval is evil
It depends on the object which holds the function. For the global scope use : window[action](). Otherwise, replace window with the name of your object : myObject[action](). However, this solution is not suitable for functions declared inside a private scope :
function f(fnName) {
function a() { alert('a') };
function b() { alert('b') };
fnName(); // error
}
In this case, you could use eval like this (⚠ keep control over inputs ⚠) :
function f(fnName) {
function a() { alert('a') };
function b() { alert('b') };
eval(fnName)();
}
Otherwise you could wrap them inside an object like so :
function f(fnName) {
var wrapper = {};
wrapper.a = function () { alert('a') };
wrapper.b = function () { alert('b') };
wrapper[fnName]();
}
f('a'); // alerts "a"
f('b'); // alerts "b"
Related
I created a javascript and added it to a page like this:
(function (window, google, List){
var myfunction = (function(){}
myfunction.prototype = {
hint: function(){alert('a good advise');}
})
}(window, google, List))
I added the needed js files, and it works! it will show the result after loading when instatination id like
var myfancything = myfunction.create();
I am getting the result after page load.
BUT! I would expect that if i then open the console and type
myfancything.hint();
I would see the alert.
I know I was able to do that the other day, but I don't know how I achieved it!
so I would like to use the prototypes in the browser console, can you guys give me a hint how to do that?
Since you declared myfunction as a local variable inside the IIFE, it's not accessible outside that scope. Get rid of the IIFE if you want to make it global, or assign to window.myfunction.
A function declared inside another function is not accessible from the outside by default :
f();
try {
g("u");
} catch (e) {
console.error(e);
}
function f () {
g("f");
function g (caller) {
console.log(caller, "called g");
}
}
If you want the inner function to be public, you have to declare it explicitely :
f();
try {
g("u");
} catch (e) {
console.error(e);
}
function f () {
g("f");
window.g = g;
function g (caller) {
console.log(caller, "called g");
}
}
I just can't reach the function inside function using only HTML.
How to call setLayout() using only HTML or is it able to call only in Javascript?
<button onclick="customize.setLayout('b.html');">Click Please</button>
Javascript:
function customize() {
function setLayout(text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
}
}
It isn't possible to call setLayout at all.
Functions defined in other functions are scoped to that function. They can only be called by other code from within that scope.
If you want to to be able to call customize.setLayout then you must first create customize (which can be a function, but doesn't need to be) then you need to make setLayout a property of that object.
customize.setLayout = function setLayout(text) { /* yada yada */ };
Multiple ways to call a function within a function. First of all, the inner function isn't visible to the outside until you explicitly expose it Just one way would be:
function outerobj() {
this.innerfunc = function () { alert("hello world"); }
}
This defines an object but currently has no instance. You need to create one first:
var o = new outerobj();
o.innerfunc();
Another approach:
var outerobj = {
innerfunc : function () { alert("hello world"); }
};
This would define an object outerobj which can be used immediately:
outerobj.innerfunc();
if you insist to do it this way, maybe define setLayout and then call it,
something like this:
<script>
function customize(text, CallSetLayout) {
if (CallSetLayout) {
(function setLayout(text) {
//do something
alert(text);
})(text);
}
}
</script>
<button onclick="customize('sometext',true);">Click Please</button>
then you can decide if you even want to define and call setLayout from outside
Simple answer: You can't call setLayout() with this setup anywhere!
The reason being, setLayout() will not be visible outside of customize() not even from other JavaScript code because it is defined locally inside customize() so it has local scope which is only available inside customize(). Like others have mentioned there are other ways possible... (^__^)
You can return the response of setLayout() by returning it as a method of customize() and use it in your HTML like customize().setLayout('b.html'); e.g.
<button onclick="customize().setLayout('b.html');">Click Please</button>
JavaScript:
function customize() {
var setLayout = function (text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
};
return {
setLayout: setLayout
};
}
Another Approach
You can also define your main function i.e. customize as Immediately-Invoked Function Expression (IIFE). This way you can omit the parenthesis while calling its method in HTML section.
<button onclick="customize.setLayout('b.html');">Click Please</button>
JavaScript
var customize = (function () {
var setLayout = function (text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
};
return {
setLayout: setLayout
};
})();
You need to treat it as object and method
<button onclick="customize().setLayout('b.html');">Click Please</button>
Sorry I had to edit this code for more clarification
function customize() {
this.setLayout = function setLayout(text) {
var selectedLayout = text;
layout += selectedLayout;
$.get(layout, function (data) {
$("#layout-grid").html(data);
});
}
return this;
}
What does below code mean.As for as i understand. if there is variable $wnd.document.bg_instance , than call the function named bg_instance. But What is function inside function ? function(a){b=a} ?
Can Some one explain the flow of below code.
if($wnd.document.bg_instance){
$wnd.document.bg_instance.invoke(function(a){b=a});
$wnd.document.bg_instance=null
}
full function
function rA() {
var b = 'js_disabled';
if ($wnd.document.bg_instance) {
$wnd.document.bg_instance.invoke(function(a) {
b = a
});
$wnd.document.bg_instance = null
}
return b
}
return b;
}
What is invoke in javascript
invoke is not a standard JavaScript function. It must be a method on the object provided by some other code in the program. What exactly it does will depend on how it is defined.
What is function inside function ? function(a){b=a}
That is an argument that is passed to the function stored in the invoke property.
See this example of passing objects around:
function myFunction(myArgument) {
myArgument(3);
}
myFunction(function (foo) { alert(foo + 1); });
Just wondering if there is anyway to fire some code when a function is called, without adding the code to the function, for example:
function doSomething(){
//Do something
}
//Code to call when doSomething is called
You can wrap the function :
(function(){
var oldFunction = doSomething;
doSomething = function(){
// do something else
oldFunction.apply(this, arguments);
}
})();
I use an IIFE here just to avoid polluting the global namespace, it's accessory.
Well, yes, it's not actually hard to do. The crucial thing is that a function's name is just an identifier like any other. You can redefine it if you want to.
var oldFn = doSomething;
doSomething = function() {
// code to run before the old function
return oldFn.apply(this, arguments);
// code to run after the old function
};
NB that it's better to do oldFn.apply(this, arguments) rather than just oldFn. In many cases it won't matter, but it's possible that the context (i.e. the value of this inside the function) and the arguments are important. Using apply means they are passed on as if oldFn had been called directly.
What about something like:
function doSomething(){
doSomething.called = true;
}
//call?
doSomething();
if(doSomething.called) {
//Code to call when doSomething is called
}
I know you said you don't want to modify the original function, but consider adding a callback. Then you can execute code based on different results in your function (such as onSucess and onError):
function doSomething(onSuccess, onError){
try {
throw "this is an error";
if(onSuccess) {
onSuccess();
}
} catch(err) {
if(onError) {
onError(err);
}
}
}
Then, when you call doSomething, you can specify what you want done with inline functions:
doSomething(function() {
console.log("doSomething() success");
}, function(err) {
console.log("doSomething() error: " + err);
});
I have a requirement where I get the anchor tags id and based on the id I determine which function to execute.. so is there anything that suites below code
function treeItemClickHandler(id)
{
a=findDisplay(id);
a();
}
You can assign a function to a variable like so:
You can also return a function pointer from a function - see the return statement of findDisplay(id).
function treeItemClickHandler(id)
{
var a= findDisplay;
var other = a(id);
other();
}
function findDisplay(id)
{
return someOtherThing;
}
function someOtherThing()
{
}
Sure, functions are first class objects in JavaScript. For example, you can create a map (an object) which holds references to the functions you want to call:
var funcs = {
'id1': function(){...},
'id2': function(){...},
...
};
function treeItemClickHandler(id) {
if(id in funcs) {
funcs[id]();
}
}
As functions are treated as any other value, you can also return them from another function:
function findDisplay(id) {
// whatever logic here
var func = function() {};
return func;
}
functions are normal javascript values, so you can pass them around, (re)assign them to variables and use them as parameter values or return values for functions. Just use them ;) Your code is correct so far.
You can map between ids and functions to call in a number of ways.
One of the simpler ones is to create an object mapping ids to functions, and find the function to call from that object (this is in essence a nicer-looking switch statement).
Example:
function treeItemClickHandler(id)
{
var idMap = {
"some-id": findDisplay,
"another-id": doSomethingElse
};
if (!idMap.hasOwnProperty(id)) {
alert("Unknown id -- how to handle it?");
return;
}
// Call the corresponding function, passing the id
// This is necessary if multiple ids get handled by the same func
(idMap[id])(id);
}
function findDisplay(id)
{
// ...
}
function doSomethingElse(id)
{
// ...
}