passing a function as a parameter? - javascript

Here is my event and as you can see I want to send a function with it as a parameter.
onclick="deleteItems('image', 'size', function(){GetImageSize();})"
The delete function is in a js file. In my js file I want to call my GetImageSize() function.
var deleteItems = function(module, controller, callback) {
callback(); // ??????????
}
I want to do this so I can rebuild my table when my ajax call has finished.
Hope you guys can help me
Regards Örvar

You can refer to the function, without calling it--just don't use the ending parens. The parens mean you're calling the function. In the case of passing the function into another function as a callback you want to leave the parens off. (And you don't need the anonymous function declaration around it.) It should read:
onclick="deleteItems('image', 'size', GetImageSize);"

JavaScript functions are first class objects. You could store functions in variables and pass them around as arguments to functions. Every function is actually a Function object.
Therefore, if you have a GetImageSize() function, you can simply pass it to the deleteItems() function just like any other variable:
deleteItems('image', 'size', GetImageSize);

Related

Passing $('.class').each a function as arugment fails to run function

Here is the code that works perfectly
$('.picture').each(function(index) {
hideYourself(index);
});
However, when I try
$('.picture').each(hideYourself(index));
it doesn't run hideYourself. I thought it was maybe because I wasn't defining index but I don't define it when I pass it an anonymous function. CodePen of the whole program.
I know this might be a silly thing to be worried about but I am just confused on why passing .each a named function fails but passing it an anonymous function that calls my named function it works.
Use:
$('.picture').each(hideYourself);
Because each take one parameter function as argument but you actually invoking function using hideYourSelf(index) it invoked the function and returns the function return value as parameter to each.
You can achieve it as:
$('.picture').each(hideYourself);
or another way to achieve the same behavior is:
$('.picture').each(hideYourself());
function hideYourself(){
return function(index){
//hide here
}
}
first way is easy and better.

Javascript: How to get callback's parameters

I'm trying to somewhat replicate the functionality of forEach so that I can understand it better. In forEach you can pass it in an anonymous function with a parameter 'item' and then it would give you the items in the array. So how is this done exactly? Below I have a function print where I call another function a with an anonymous function as parameter. So how can I extract the parameter called 'param' from the anonymous function and use it in a's definition.
function print() {
var param = 'param1'
a(function(param) {
console.log('execute a')
})
}
function a(fn) {
//how can i access the fn's parameter list here?
//execute fn and do something with its parameter
fn()
}
print()
What I'm trying to accomplish: Run the function "a" and execute the anonymous function passed into it along with its parameters
You're completely misunderstanding parameters.
Your callback is a function. Its parameters are passed by the code that calls it (in a()), just like any other function.
If you want to pass a parameter to a(), you should pass it like any other parameter.
The fact that your callback's parameter happens to have the same name as a local variable is completely irrelevant.

Javascript closures and callbacks - variable value doesn't persist after the callback

I'm wondering why the variable is undefined if it's initialized within a callback function.
Pseudo code:
var name;
//callback function:
function(givenName) {
name = givenName;
}
alert(name) // undefined
The callback function is called from a different module that passes the givenName, and within the callback function name is defined as it should, but not outside the callback function. I'm curious to know how this works and how to get around it. Any articles or answers are more than welcome! thanks.
When this function is called from another context and you want to affect variables in the actual scope you will need to pass the context when calling this method.
Therefore you should use call or apply and pass the desired context as first parameter.
Hope this helps

Not needing brackets when not passing any arguments

I am creating a function with this line:
window.Spark = window.$ = function(selector, context) { ... };
But I am having a problem (obviously), if I call a function like this $('p').content('Hi!'); then everything works great because I am treating $ like a function. However, when I run a function like this $.ajax('get', 'example.txt'); I get this error $.ajax is not a function. This is because I am not including the brackets. Does anyone know a way around this? I saw in the jQuery source that they have a function within a function. Is this the sort of thing I need?
Thanks for any help you can offer.
I assume by brackets you mean parentheses.
In jQuery, $ is a function with properties.
You can replicate this type of behavior simply by assigning properties to $:
window.Spark = window.$ = function(selector, context) { ... };
$.ajax = function(method, url) { ... };
Functions are first class citizens in JavaScript, i.e. you may treat them like objects are being treated in OOP. It's possible to assign properties to them and those properties may be functions in turn.
So, $.ajax is really nothing else then the property ajax that's a "member" of the function (object) $ that happens to be a function.
So long.
If you put a function within a function it's local to the outer function, so it's not possible to call it from outside the function.
A function in Javascript is an object like any other, so you can add properties to it, and the property can be a function:
var $ = function() { alert("1"); };
$.ajax = function() { alert("2"); };
$(); // shows "1"
$.ajax(); // shows "2"
Um.... $.ajax needs to be a function to be called like that. So either define the 'ajax' function or don't use it.
I'm pretty sure it has nothing to do with "not including the brackets," whatever that means. In jQuery, the identifier $ represents a function object that has several attributes. One of these attributes is ajax, which contains a function that performs an AJAX call. Just because you call your own function $ doesn't mean it automagically gets the functionality of jQuery. If you want $.ajax to be a function, you'll need to define it.

What's the meaning of "()" in a function call?

Now, I usually call a function (that requires no arguments) with () like this:
myFunction(); //there's empty parens
Except in jQuery calls where I can get away with:
$('#foo').bind('click', myFunction); //no parens
Fine. But recently I saw this comment here on SO:
"Consider using setTimeout(monitor, 100); instead of setTimeout('monitor()', 100);. Eval is evil :)"
Yikes! Are we really eval()-ing a string here? I guess I don't really understand the significance and implications of 'calling' a function. What are the real rules about calling and referring to functions?
In JavaScript functions are first-class objects. That means you can pass functions around as parameters to a function, or treat them as variables in general.
Let's say we are talking about a function hello,
function hello() {
alert('yo');
}
When we simply write
hello
we are referring to the function which doesn't execute it's contents. But when we add the parens () after the function name,
hello()
then we are actually calling the function which will alert "yo" on the screen.
The bind method in jQuery accepts the type of event (string) and a function as its arguments. In your example, you are passing the type - "click" and the actual function as an argument.
Have you seen Inception? Consider this contrived example which might make things clearer. Since functions are first-class objects in JavaScript, we can pass and return a function from within a function. So let's create a function that returns a function when invoked, and the returned function also returns another function when invoked.
function reality() {
return function() {
return function() {
alert('in a Limbo');
}
};
}
Here reality is a function, reality() is a function, and reality()() is a function as well. However reality()()() is not a function, but simply undefined as we are not returning a function (we aren't returning anything) from the innermost function.
So for the reality function example, you could have passed any of the following to jQuery's bind.
$('#foo').bind('click', reality);
$('#foo').bind('click', reality());
$('#foo').bind('click', reality()());
Your jQuery bind example is similar to setTimeout(monitor, 100);, you are passing a reference of a function object as an argument.
Passing a string to the setTimeout/setInterval methods should be avoided for the same reasons you should avoid eval and the Function constructor when it is unnecessary.
The code passed as a string will be evaluated and run in the global execution context, which can give you "scope issues", consider the following example:
// a global function
var f = function () {
alert('global');
};
(function () {
// a local function
var f = function() {
alert('local');
};
setTimeout('f()', 100); // will alert "global"
setTimeout(f, 100); // will alert "local"
})();
The first setTimeout call in the above example, will execute the global f function, because the evaluated code has no access to the local lexical scope of the anonymous function.
If you pass the reference of a function object to the setTimeout method -like in the second setTimeout call- the exact same function you refer in the current scope will be executed.
You are not doing the same thing in your jQuery example as in the second setTimeout example - in your code you are passing the function and binding the click event.
In the first setTimout example, the monitor function is passed in and can be invoked directly, in the second, the sting monitor() is passed in and needs to be evaled.
When passing a function around, you use the function name. When invoking it, you need to use the ().
Eval will invoke what is passed in, so a () is required for a successful function invocation.
First of all, "()" is not part of the function name.
It is syntax used to make function calls.
First, you bind a function to an identifier name by either using a function declaration:
function x() {
return "blah";
}
... or by using a function expression:
var x = function() {
return "blah";
};
Now, whenever you want to run this function, you use the parens:
x();
The setTimeout function accepts both and identifier to a function, or a string as the first argument...
setTimeout(x, 1000);
setTimeout("x()", 1000);
If you supply an identifier, then it will get called as a function.
If you supply an string, than it will be evaluated (executed).
The first method (supplying an identifier) is preferred ...

Categories