accessing a hidden function with javascript - javascript

Hi I have a few custom functions wrapped in jQuery's document.ready function. Most of these functions are utilized from within that function and work, but there is a case where I would like to access a function contained within this from the global scope. How can I do this? can i do something like:
jQueryReadyScope.myFunctionName('paramaters');
Thank you very much.

Nope, but you can name the function and pass it to .ready():
var myFunctionName = function (params) {
// do things
}
// pass as callback to ready function
jQuery(document).ready(myFunctionName);
// access directly like any other function:
myFunctionName('paramaters');

That's a scope issue, and all you need to do is specify the namespace. In this case, you're talking global so we'll use window.
window.myFunction = function() { ... stuff }

To access it from the global scope it would need to be assigned to a global variable, either by declaring it outside your document ready or by assigning it as a property of window:
var yourGlobalFunction1 = function() { ... }
$(document).ready(function() {
function privateFunction() { ... }
window.yourGlobalFunction2 = function() { ... };
yourGlobalFunction1();
privateFunction();
yourGlobalFunction2();
});
yourGlobalFunction1();
// and then at some later point AFTER the document ready has run,
// e.g., in response to some event:
$("#someelement").click(function() {
yourGlobalFunction2();
});

Related

How can I execute a function using a variable name?

Here is my code:
$(function(){
function myfunc(){
alert("executed");
}
var function_name = "myfunc";
window[function_name]();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As you can see, that function is not defined. Why? And how can I make it working?
The function is not defined in the global scope so it’s not a member of the window object.
You can attach the function to the window object like this.
$(function(){
window.myfunc = function(){
alert("executed");
};
var function_name = "myfunc";
window[function_name]();
})
It works only for global functions, because the scope is identically with the window object.
You could assing a function to a wanted property of the window object, just as to any other object.
function myfunc(){
alert("executed");
}
$(function(){
var function_name = "myfunc";
window[function_name]();
window.foo = _ => console.log('foo');
window.foo();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
While the direct answer to your question is that your function wasn't defined as a Global and so, attempting to call it as a property of window fails, putting your function into Global scope is not really a good answer.
Instead, make the function a method of a user-defined object (that can be put into any scope you like) and call the function as a property of that object:
// Immediately-Invoked Function Expression (IIFE)
// that keeps all of its contents out of the Global scope
(function(){
let functionHolder = {
someFunction : function(){ console.log("You did it!"); }
};
// Set up a variable that has the same name as the function
let funcName = "someFunction";
// Call the function via the object
functionHolder[funcName]();
})()

I don't understand why the "this" keyword doesn't work as I expect

What I want to do is to execute the create_tag function when a specified condition is satisfied. I am referring to this function as a method of an object, in this case document.body, by setting as its method an external function, "create_tag(..)". The problem is inside this function I have a "this" keyword which I would expect to refer to the method's parent, document.body. Instead it doesn't seem to work. I tried replacing "this" with "document.body" in the function so the problem should be caused by "this".
Here is the code:
xmlDom=xmlhttp.responseXML;
hint_ul=document.getElementById("hint_ul");
personaggi=xmlDom.documentElement.getElementsByTagName("personaggio");
for(i=0;i<personaggi.length;i++){
personaggio=personaggi.item(i);
name=personaggio.childNodes[1].firstChild.nodeValue;
if(name.substr(0, str.length).toLowerCase()==str.toLowerCase()){
document.body.crea_li=create_tag(name);
}
}
}
function create_tag(inner){
a=document.createElement("a");
a.innerHTML=inner;
this.appendChild(a); }
this will be window when called like that.
To get its this as the body element, call it like so...
document.body.crea_li = create_tag.call(document.body, name);
Nowhere in your code is create_tag assigned as a method of document.body. The closest you get is with the line document.body.crea_li=create_tag(name);, but what's actually happening here is that you are executing create_tag as a member of the global object, and the result of that operation is assigned to document.body.crea_li.
You could make a reference to this outside the function body - referencing it within the scope later:
var self = this;
function create_tag(inner){
a=document.createElement("a");
a.innerHTML=inner;
self.appendChild(a);
}
This could be a nice trick. When I make complicated javascript objects involving many objects and functions, at the top of the object I create:
var self = this;
as that will live within the scope, the root object is always accessible.
Here is a working example of how I would implement this:
SomeReallyComplexThing = function() {
var self = this;
var foo = 'bar'
this.fooThing = 'Other thing'
this.setSomeData = function(){
console.log('Some data set', arguments)
}
this.makeMassiveCall = function() {
var completeFunc = function(){};
var url = '/some/endpoint.json';
var requestData = {};
jQuery.get(url, requestData, function(data) {
/*
* Data has come back
*/
self.setSomeData(data)
completeFunc(data);
});
}
}
//outside the scope
s = new SomeReallyComplexThing()
s.fooThing() //visible
s.self //undefined
this in javascript is a sqirrely fellow. The idea is this refers to the current function context.
This means that when your running code inside the function this refers to that function's context, which does not have an appendChild method.
Normally you use a closure to keep a reference to the calling context around, something like this
var _self = this;
var result = func();
function func()
{
// _self is the calling context, this is the current context
}
Or you could pass a reference to the calling context:
document.body.crea_li=create_tag(name,this);
function create_tag(inner, context) { context.body.appendChild(...) }
this is referring to the function's parent, but its parent is actually the window object, not the document object or document.body. this actually refers to wherever context the function is called from, and in my opinion you should avoid using it to call methods just for that reason because it can be difficult to see what this is actually referring to. For example, if you called a function using this from another function, it would refer to the context within that function.
This example might help show what's going on:
var hello = function() {
alert( this.message );
}
window.message = "hello!";
hello()
You could document.body directly in the code like you suggested before, or you could pass another parameter that tells the function where to append the created tag:
function create_tag(inner, elementToAddTag){
a=document.createElement("a");
a.innerHTML=inner;
elementToAddTagTo.appendChild(a);
}

How can i access the functions from other JS files

(function () {
pm.view.functionName= function () {
function nameFunction() {
var something;
return something;
}
return win;
};
})();
I am in another JS file and i want to call this nameFunction()... how can i do this. I tried...
pm.view.functionName().nameFunction()
But i get an error called, cannot call function in the Object. How can i access the functions from other JS files.
The function nameFunction exists in the scope of the function functionName. You cannot access it from outside that function.
If you want to do so, you'll have to explicitly say so:
pm.view.functionName.nameFunction = function() {
var something;
return something;
};
You could then access it as pm.view.functionName.nameFunction().
nameFunction is local to pm.view.functionName and you cannot access it, just like you cannot access local variables. You can call nameFunction() only when being inside pm.view.functionName.

Calling nested function when function name is passed as a string

I'm trying to access a nested function by passing the function name in as a string and then calling it. Eg, see this post
function outer(action){
window["outer"][action]();
function inner(){
alert("hello");
}
}
outer("inner");
However it doesn't work. Error:
window.outer[action] is not a function
How to make this work, or an alternative way of calling a nested function.
The reason for this is that I am trying to hide a bunch of functions that are called by an iframe inside a functions scope.
function outer(action){
var inner = {
func1: function() {},
func2: function() {},
func3: function() {},
// ...
}
inner[action]();
}
outer("func1");
In that way you are trying to access the "inner" property of the "outer" function (outer.inner) that is not defined. The only way to do that is by using eval:
function outer(action){
eval(action+"()");
function inner(){
alert("hello");
}
}
outer("inner");
But remember eval is evil is some situations so be careful.

How to execute a YUI function from Javascript?

How can i call a YUI function that is wrapped inside a YUI().use from javascript?
example
Below is a YUI function "runShowAnim" which executes animShow.run(); for an animation effect...
var runShowAnim = function(e) {
animShow.run();
};
I want this effect to happen when i validate something in a javascript function. I tried to call it as below. But it doesn't seem to work.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
I achieved this by sandwiching the YUI function completely inside a function and calling that function..
var runShowAnim = function() {
YUI().use('anim', 'node', function(Y) {
var animShow = new Y.Anim({
node: '#msgArea',
to: { height: 50,opacity:1 }
});
animShow.run();
});
};
now i can call runShowAnim without any problem like in the below sample function..
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim();
}
If you want to call a function, you have to suffix the function name with () and include 0 or more comma separated arguments between them.
runShowAnim();
If the function doesn't have global scope (as yours will have if it is declared inside a function passed to use()) and not passed outside in some way then you can only do this from the same scope.
I think you're missing the parentheses.
function notifyUser(message) {
document.getElementById("msgArea").innerHTML = message;
runShowAnim(); // right here
}
YUI.thefunction()?
I think you need to call it with namespace too
something similar to
var X = function(){};
X.Y = function(){};
X.Y.Z = function(){};
X.Y.Z.foo = function(e){alert(e);}
//foo("me");<-error
X.Y.Z.foo("me");
If you want to call a function that has been defined inside the closure (the function passed as the last parameter to YUI.use) from outside it, you need to expose the function globally.
Either define a global variable outside the closure and assign your function to it, or assign your function to the window object
i.e.
var runShowAnim;
YUI().use(function(e){
runShowAnim = function(){alert('called');}
});
runShowAnim();

Categories