jQuery .click() function called automatically - javascript

I have an event listener set up on a button using jQuery, and for some reason the function within the click listener is called without the button being clicked. I know that usually functions are anonymous in listeners, but it won't work as an anonymous function. The function I am calling also has to accept parameters, which is why I don't think I can just call a reference to the function. Any ideas on how I can fix the problem of the function getting called without a click even registered and still pass the necessary parameters to the function?
$('#keep-both').click(keepBothFiles(file, progress, audioSrc));
calls this function
function keepBothFiles(file, progress, audioSrc) {
...
...
}

You're referencing the function incorrectly. Try this instead:
$('#keep-both').click(function(){
keepBothFiles(file, progress, audioSrc);
});
Whenever you use the syntax funcName(), the () tell the interpreter to immediately invoke the function. The .click method requires that you pass it a reference to a function. Function references are passed by name only. You could also do:
$('#keep-both').click(keepBothFiles);
But you can't pass it your other arguments. It's given an event object by default

You must pass a function reference to the .click() function, not the result of calling a function. When you include the () like this keepBothFiles(...) at the end of the function name, you are telling javascript to execute the function now. When you just use the name of the function like keepBothFiles, you are getting a reference to the function (which can be called later).
You are currently calling your function immediately and then passing the return value of that function (which is not a function reference) to the .click() function, thus it does not do what you want.
The click handler callback function is passed exactly one parameter (the event) in jQuery so you cannot have it call your keepBothFiles(file, progress, audioSrc) function directly like you have it.
Instead, it could be done like this with a second wrapper function:
$('#keep-both').click(function(e) {
keepBothFiles(file, progress, audioSrc);
});

Related

Javascript syntax confusion [beginner]?

I don't understand what view("") does in the following javascript method that is part of Model object:
addView: function(view) {
this.views.push(view);
view("");
}
view(object) method is not defined anywhere...
view(object) method is not defined anywhere
The function that view is referring to is passed as argument to addView. This is also called a callback. A callback is a function (A) that is passed to another function (B) and is supposed to be called by that function (B).
So somewhere, there might be code that looks like
obj.addView(function(v) {
// using anonymous function expressions is a pretty common way to define
// callbacks
});
or
function someFunctionName(v) {
// any function will do, no matter how it is defined
}
obj.addView(someFunctionName);
Functions are first class objects in JavaScript and can be passed around like any other values.
It looks like it's passing in a function called view. Then it calls the view function.
Functions are first class citizens in JavaScript and can be passed as parameters to other functions.
addView: function(view) {//view is a function itself that is passed into the current function.
this.views.push(view);
view("");
}
The call could be like this
someObj.addView(function(par1){alert("I am a function too")});
Assume you have function view , if you call the view function without passing parameter in view(), then it returns like undefined, In such case we need to initialise the passing parameter value from function view("")
function view(passedData){
alert (passedData);
}

JavaScript .click() unintentionally auto-starting

I created a custom variable/function that I am trying to execute when an element is clicked. For some reason, it decides to display onload and ignores the .click(). I've spent a while now trying to figure this out, but I'm not having much luck.
Here's my custom function:
var movebox = function (entry) {
$imagebox.css('left' , '0');
$('#wr').append(entry);
};
I'm attempting to call it like this, but it calls it when the page loads instead.
$l3.click(movebox('test'));
You're calling the movebox function immediately instead of passing the function as a reference to the click event handler. This is a common mistake in JavaScript. Instead, pass in your function inside of an anonymous function, like so:
$l3.click(function() {
movebox('test');
});
As an aside, the same mistake is oftentimes made with setTimeout, setInterval, addEventListener, and the infamous eval. Remember, when treating functions as arguments to another function, be sure to wrap them in anonymous functions.
You are calling the movebox then passing the returned value to click event handler, in this case you can use the .on() event registration helper to pass a data element to the event handler which can be accessed using the event object.
Try
var movebox = function (e) {
$imagebox.css('left' , '0');
$('#wr').append(e.data.entry);
};
$l3.on('click',{ entry: 'test'}, movebox);

Why does a Javascript function call not contain '()' after the name of the function?

window.onload = function() {
document.getElementById('clickMe').onclick = runTheExample;
}
function runTheExample() {
alert('running the example');
}
This is a simple event handler for the onclick event for an html input button with id = clickMe.
In line 2, why is the call to function runTheExample not immediately followed by ()? I thought that to call a function you must pass it any variables/objects it expects in an open/close parenthesis, and if the function isn't expecting anything, you must still include the open and close parenthesis like runTheExample().
document.getElementById('clickMe').onclick = runTheExample;
The intention here is not to call runTheExample() but to assign the reference to the function runTheExample to the onclick event.
Internally, when the onclick event is fired, Javascript is able to call the function runTheExample through the reference you provided on the code above.
Snippet
var myFunction = function() { return 42; };
// Assigning the reference
myObject.callback = myFunction;
myObject.callback(); // Has the same effect as calling myFunction();
// Assigning by calling the function
myObject.callback = myFunction();
myObject.callback; // Returns 42
myObject.callback(); // Exception! Cannot call "42();"
That's not Javascript-specific. Passing functions by reference is available in many languages.
You use the parenthesis only to invoke (call) a function. When you're assigning it to onclick, you're merely passing it by reference.
To better understand this, think about the other method of declaring a function:
var runTheExample = function () {
alert('running the example');
}
Regardless of what method you use, runTheExample will contain a reference to the function (there are some differences, like the function reference not being available before assignment, but that's a different story).
Functions are objects in javascript. That line sets the onclick property of the click me element to the runTheExample function, it doesn't call that function right then.
var a =runTheExample; //sets a to runTheExample
a(); //runs the runTheExample function
So when the function name is referenced without the () it is referring to the function object, when you add the () it is a call to the function, and the function executes.
It's not calling it, but rather setting the property onclick. When a call is made to onclick(), it will then run the function you've defined. Note however that the context of this will be the object that calls it (document.getElementById('clickMe')).
You're not calling the function here. You're setting the function as an event handler, and the function is not actually called called until the event is fired. What you've written references the function; that's a different notion than actually calling it.
In this case, the runTheExample function is being treated as a variable and being assigned to the onclick event handler. You use () after a function name to call a function. If you added them here, what would happen is that runTheExample() would be called once during load, showing an alert, and then a null value would be assigned to the onclick handler.
Because it binds runTheExample to onclick event.
When you add () it triggers the function.

onclick call with params

I've got a function, like this:
menu[0].onclick = function() {
filters.reset_all();
clients.get();
}
So it's called when user clicks on the first menu element. Now I need to call it form the other place and what I've done is this:
if (li.onclick) { //li and menu[0] above are the same
li.onclick.call();
}
and it works well.
But now I need to pass some params to onclick function. I've tried this .call(some_param); but arguments array in onclick is empty.
What am I doing wrong?
edit: changed into this:
menu[0].onclick = function(arg) {
console.log(arg);
filters.reset_all();
clients.get();
}
and
li.onclick.call(li,param);
still nothing
The first argument to .call() is the value for the this pointer. The 2nd, 3rd, etc... arguments get passed to the function. You only need to use .call() if you're explicitly trying to set the this pointer. Otherwise, you can just directly call the function li.onclick().
Event handlers are generally called by the system and when that happens, they are passed the event object as the first argument. If you want a function available that takes different arguments, you should create your own function for that and not use the event handling function. Your event handler can also call this other function if desired.
menu[0].onclick = function() {
myFunc("aaa");
}
function myFunc(arg1) {
// do whatever here
filters.reset_all();
clients.get();
}
if (li.onclick) {
myFunc("bbb");
}
it should be
call(object, param1, param2, param3...);
In your case you can write
li.onclick.call(li, param1);
The first parameter of call() is the context (in this case this) the rest of the parameters go into the arguments array in order. If you use apply() instead of call then you have just two parameters: apply(this, arguments_array)

Why wrapping into a function is required in .change() of jQuery?

Why this works in jQuery :
$('#selCars').change(function(){
alert( "I have changed!" );
})
but not this one :
$('#selCars').change(alert( "I have changed!" ) );
You pass a function reference to .change(). Your second example just has code there, not a function reference.
Your first example works because it passes a function reference which IS what is required.
A function reference is required because this is a callback that will be called at a later time. The .change() function which executes immediately needs to save the callback reference into it's own variable and then call it later when the change event actually occurs. To do that, it needs a function to call at that later time, not a raw piece of code.
And, the other answer is because, .change() was written to require a function reference. That's how the developers that spec'ed and wrote it designed it. If you want it to work, you have to follow their rules.
Because it's a callback, i.e. you're passing something that be called back later, so what you've to pass is a reference to a function, and that reference will be stored and called when the event will fire.
The change method doesn't store some code, it stores only a pointer to the function. Your function is called an event handler.
It's because .change() attaches an event handler to an element. The handler won't be called until the event has occurred.
Since in JavaScript, functions are just another datatype, you could also do this:
var handler = function(event) {
alert("I have changed!");
}
$('#selCars').change(handler);
Note that handler is a function, Whereas alert() would just return undefined.

Categories

Resources