I need some explanation about some syntax - javascript

I have seen this kind of code in one of Google's google maps documentation. My question is about the listener. Instead of the callback function passed immediately after the 'click' action the showArrays() function is called but not passed nothing as parameter. On the other hand showArrays() function uses event as parameter. Please explain me this kind of calling the function.
element.addListener('click', showArrays);
//some code here
}
function showArrays(event) {
// some code here
}

Think of the names of functions as variables themselves. showArrays is a variable, that, when given an event, does something with it.
You can pass the functions name as a parameter to addListener so that it can call the callback when the element is clicked on. It's important to note that you are not calling the function in the first line, only passing a reference to that function.
You can show this property in the browser's console with this test:
function test() { console.log("Test was called"); }
Notice if you say var x = test nothing is printed to the console. But if you say var x = test() you see the print. Finally, if you do var x = test; x() you will see the print out, because you called the test function after assigning it a new name.

Notice that in the element.addListener('click', showArrays) line, showArrays does NOT have brackets after it. That means it's not being called. Instead, the entire function is being passed as a parameter to the addListener method.
Event listeners in JS will take the handler function you provide when you attach them with addListener (or addEventListener, more commonly), and, when the event occurs, they will call that function and pass an event object to it.
In other words, showArrays is not being called until the element is clicked, and all event listeners inherently get passed an event object at that point, detailing the specific properties of the event.

One of the syntax cases for describing a function is:
var showArrays = function (event) {
// of the code here
}
and it is precisely this argument value that the addEventListener method uses, and even other functions such as setTimeout or setInterval, among others.

addEventListener method always sends the "event" object as an argument to the callback function. When you use the anonymous function, it is obvious to see it:
element.addEventListener('click', function(event) {
// some code here
});
But when you send to the addEventListener method a link to the function you want to be called when the event occures (in your case it is a link to showArrays function), addEventListener sends "event" object as an argument to this function just on itself. So, although it's not obvious to see it, but the "event" object is being sent to showArrays function automatically.
element.addEventListener('click', showArrays); // the event object will be sent automatically
And you will have an access to the "event" object inside the showArrays function. But, of corse, in showArrays function declaration you should have a parameter for catching the "event" object.
function showArrays() {} // it's not going to work
function showArrays(event) {} // it will work

Related

Arrow function in onClick method? [duplicate]

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

JavaScript: Event Listeners with Callbacks and Parameters

I have an event handler which (a) requires parameters, and (b) calls a callback function via window.setTimeout. I use bind to attach the event handler.
The called function is called with additional parameters. I have tried both callback(parameters) and `callback.call(this,parameters).
Below is a code sample:
var element=document.querySelector('h1');
element.onclick=function(e) {
delay(test.bind(element,'from original','also from original',e));
}
function test(a,b,c,d,e) {
alert(this); // element
alert(a); // from original
alert(b); // also from original
alert(c); // event
alert(d); // from delayed
alert(e); // also from delayed
}
function delay(callback) {
window.setTimeout(delayed,100);
function delayed() {
// callback.call(this,'from delayed','also from delayed');
callback('from delayed','also from delayed');
}
}
I my testing, I find that callback gets the parameters in the following order:
Parameters from the original function
The event itself
Parameters from the function calling the callback
Further, I find that the callback function has this set to the original element, even if I call it using .call with the this argument set to anything (even null).
I can handle this certainty, but I am confused as to how this is formally handled. I can’t find anything in the documentation which discusses an event listener with a callback.
The question is:
Where is the ordering of the parameters documented?
Where does this come from, and why does it seem to ignore any attempts to change ie?
Thanks
As you can see by the bind() documentation:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
So this line: test.bind(element,'from original','also from original',e)
will return a function that when called will use those provided arguments first, and any subsequent arguments after those. So when calling your function, it will result in the order you list above.
As for this, the problem is that you are using setTimeout() after the bind, which is why you might not be getting what you are expecting. You can read more about setTimeout() and this here.

Running jQuery declared function with .on function

Currently this function works:
$("#email_address_input").on('focusout', function(){
emailValidationCheck($(this));
});
function emailValidationCheck(e){
...
}
So basically, if the email address input element is focused out, then an anonymous function runs, which calls the declared function emailValidationCheck (and of course, that declared function takes as an argument the email address input element).
That anonymous function feels redundant. All it does is call the declared function, so it seems to me like it should be taken out.
So, what I tried to do was call the declared function directly upon the event firing, as opposed to calling the anonymous function, which in turn calls that declared function. Like this (warning, it doesn't work as expected):
$("#email_address_input").on('focusout', emailValidationCheck($(this)));
Question: How can I get this to work? Or is the original answer best practice? Basically what I am trying to do is: when the focusout event fires off on the specified element, I want to execute the emailValidationCheck function, where the passed in argument is the element where this all this stuff is happening on.
Thanks!
You don't need to use anonymous functions as callbacks for events. You can easily call a defined function without using the () precursor (because including that will essentiall pass the return value of emailValidationCheck to the callback, rather than the function reference itself). For example:
$("#email_address_input").on('focusout', emailValidationCheck);
Now, your emailValidationCheck function will receive the event in the e variable that you define in the function constructor.
Because the function has been bound as a callback, $(this) is also available within it. For example:
function emailValidationCheck(e)
{
console.log( e ); // logs the event
console.log( $(this) ); // logs the jQuery object that lost focus
}
jsFiddle Demo
That's not how javascript works. The .on() function wants a function as a parameter. You can either pass an anonymous function or the name of a function. As soon as you put () at the end, it executes the function inline and passes the result to the .on() function.

What is the meaning of 'function(event)' in js

I don't know the meaning of the sentence 'function(event)'
Event.add(apple,'click',function(event) {
Event.stopPropagation(event);
});
Isn't the argument 'event' is the unique keyword of javascript?
Is keyword can be an argument of some function?
I understand the meaning of below code :
function(test) {
alert(test);
}
But I don't understand this one :
function(event)...
Can any one give an explanation about that to me?
The event object is always passed to the handler and contains a lot of useful information what has happened.
Different types of events provide different properties. For example, the onclick event object contains:
event.target - the reference to clicked element. IE uses event.srcElement instead.
event.clientX / event.clientY - coordinates of the pointer at the moment of click.
Information about which button was clicked and other properties.
Please visit this link.
It answers all your questions very simply
Source http://javascript.info/tutorial/obtaining-event-object
Example:
Like if in HTML you have assigned an event like this
<button onclick="alert(event)">See the event</button>
then
function alert(event) {
// event.type contains whether this event was invoked in the result of a click etc
// event.target would contain the reference to the element which invoked this method/event
}
It is an anonymous function, that is a function without name, that sends the event object. That object contains information about the event itself. It is always passed as first object/variable.
It is defining an anonymous function object. This code:
function foo(bar) { ... }
Is functionally similar to:
var foo = function (bar) { ... };
(Except that in the first case the name foo and the creation and assignment of the function object are hoisted to the top of the scope, while in the second case only the name foo is hoisted; foo won't hold the function until the assignment executes.)
Effectively, the code you posted is calling Event.add() and passing a function to it as the third argument, but rather than declaring the function ahead of time it is creating the function object inline.
Another way to write the code block in your question is:
function handler(event) {
Event.stopPropagation(event);
}
Event.add(apple, 'click', handler);
Except that the code in your question does not introduce the handler name.
Note that there is no such method Event.stopPropagation(). However, the event object will have a stopPropagation(), so the capital E was probably a typo. It's likely that the intent was to use function (event) { event.stopPropagation(); }.
event is just a variable that's passed to event listener functions such as Event.add, element.on. It's not reserved (although Event is, which is why you can use Event.add), and you can name it whatever you like.
The event argument is used to pass information about the event that has happened (the click on apple in this case), which can be used to retrieve data about the event or manipulate it.
function(){...} is an anonymous function, which means that you don't need to name it, you can just declare it inline, and the function will be passed as an argument, as if you said
function foo (event) {
...
}
Event.add(apple, "click", foo);
but you don't need to declare it before hand. It does come at the disadvantage of not being duplicable, for instance when clearing an event handler.
Look at the event variable and you will all understand :)
function (event) {
console.log({ event });
}

javascript function(e){}, but not passing any parameter when executing

Sometimes I see functions with parameter like this:
$('#my_div').bind("mouseover mouseenter", function (e) {
console.log(e);
var el = $("#" + e.type);
var n = el.text();
el.text(++n);
});
I don't get what is being passed into the function. I would understand it if it is something like (function(e){ .... }(parameter); but it is not. Can someone shade some light
jQuery will actually call that function, since functions are first class citizen objects in JavaScript, so it can be passed as an argument. e is for event args which jQuery will provide.
This pattern is called "callback".
There's always a parameter being passed, it's just that you're not the one passing it directly. The browser is.
In this case, you're talking about the event handlers. Basically what happens is that when the event is triggered, the browser will pass an event object to the callback of the event listener (the callback you provided).
If you want to know what's inside the event object, look into this mozilla docs page https://developer.mozilla.org/en-US/docs/Web/API/Event
If you want to know how browsers handle the whole passing of event object, here's the specification: http://www.w3.org/html/wg/drafts/html/master/webappapis.html#the-event-handler-processing-algorithm look under 4) where it says "process the event E as follows"
The function isn't actually being called yet. This is telling the browser to call that function for you when the 'mouseover' or 'mouseenter' event happens. In this case, when the browser does that it will pass an event object which will get bound to the local variable e in side of the function.

Categories