Event function declaration - javascript

Im trying to understand the declaration of the event handler and the function declaration in this post: https://stackoverflow.com/a/46418688/7727532
Im pretty new to Javascript and jQuery and trying to understand. What I do know is that you declare like the following
$('#clickMe').on('click', doSomeThing(e));
function doSomeThing(e){
console.log(e);
}
The first part I dont understand is
(e) => this._handleScaling(e)
What is happening here? We catch the current object and sending it to function _handleScaling()? But why do we have "(e) =>" before?
Second part is
_handleScaling(e) {
Which if Im right is a local function inside another? Because of the underline start. So maybe the code in the link isnt telling the whole picture?

You need to give function reference rather than function's return value
Replace
$('#clickMe').on('click', doSomeThing(e));
with
$('#clickMe').on('click', doSomeThing); //e is the event object will be automatically passed on to the event handler
The first part I dont understand is
(e) => this._handleScaling(e) What is happening here? We catch the
current object and sending it to function _handleScaling()? But why do
we have "(e) =>" before?
No, _handleScaling is only passed e (event object) so that it can get access to element on which this event has been triggered using e.target since with arrow function this will refer to scope in which this arrow function is defined.

Related

Parameter of a function within the eventlistener: How can I pass it?

I am trying to pass arguments to a function inside my eventlistener for my school assignment in the code below. I am a newbie in JS and found out here Javascript event handler with parameters, that you can't just pass parameters to an eventlistener's function. But otherwise this thread wasn't much help. Simply because I don't really know JS and didn't understand it. How can I do it?
document.getElementById("Content_id").addEventListener("focus", focusFunction ("Content_id",event);});
function focusFunction(elID,event){
alert(elID+":"+event.timestamp);
}
document.getElementById("Content_id").addEventListener("focus", function(event) {
focusFunction(event);
});
function focusFunction(event) {
console.log(event.target.id + ":" + event.timeStamp); //event.target.id is more dynamic
}
<input id="Content_id" />
You need to wrap the callback into a function, otherwise it will be invoked straight away:
document.getElementById("Content_id").addEventListener("focus", (event) => focusFunction("Content_id", event));

Why can't we pass parameter in eventListener's listener function?

function myFunc(parameter1) {
//function definition
}
document.getElementById("some Id").addEventListener("click", myFunc(myparameter));
Why is it that I cant pass a parameter to myFunc() function inside the eventListener? I know I can use this way -
document.getElementById("some Id").addEventListener("click", function() {
myFunc(myparameter);
});
But why can't I do it directly ?
PS- I want to know whether the rules prescribed by W3C are to be followed directly (and I shouldn't ask this question) or is there a reason behind every rule ?
myFunc(myparameter) executes the function right now, not when the event is triggered. You want to pass a function which executes myFunc and passes the parameter when called, i.e. when the event is triggered. The most straight forward way to do that is this:
.addEventListener('click', function () { myFunc(myparameter); })
The perhaps less obvious way is Function.prototype.bind:
.addEventListener('click', myFunc.bind(null, myparameter))
You have a problem in your code. The myFunc(myparameter) executes right way. You need to call your custom function using this way:
document.getElementById("some Id").addEventListener("click", function () {
myFunc(myparameter);
});

how to create instances of a function in javascript?

Im trying to add an event listener to a object for example:
this.startLoading = function(){
this.a.addEventListener("complete", this.loadingHandler()); this gives me an error
},
this.loadingHandler = function(){
console.log("im doing something")
}
ERROR: "Uncaught Error: addListener only takes instances of
Function. The listener for event "complete" is "undefined"
However if I put the loadingHandler() function inside the scope it works, for example:
this.startLoading = function(){
var loadingHandler = function(){...}
this.a.addEventListener("complete", loadingHandler()); // this works
},
Im not sure what instances of a function means in that regard?
When you put () after a reference to a function, that means to call the function, and the value of the expression is whatever the function returns.
Your second example, that you say works, actually will not work, and you'll get the same error if the "startLoading" function is called.
Because you probably need to retain the proper context (this), what you probably need is
this.a.addEventListener("complete", this.loadingHandler.bind(this));
The .bind() method returns a function (exactly what addEventListener requires) that in turn will invoke your function such that this has the value requested.

parse data with event listener?

Is there a way to parse data to a function from the event listener ?
I have this:
div.addEventListener('mousedown',run(id),false);
function run(e,id){
console.log(id);
}
Thing is it executes straight away. The other problem is - if i want to parse the variable id, and the run function recieves e for the event, how do you parse any thing else =/ It's a bit confusing to work out what order e is (before or after your designated variables that you want to parse)
The current work around so far was to assign id to window so its basically a global... but i'm wondering if parsing via the event is possible at all ?
One way is to create a new listener function in which the id variable is already bound to the value that you want, like this:
function newListener(id) {
var listener = function(e) {
console.log(id);
}
return listener;
}
div.addEventListener('mousedown',newListener(id),false);
newListener(id) defines a new function, in which the value that the id variable had at the time is available inside that function. Then the javascript environment will call that function when the mouse button is pressed.
An event handler does not take arguments directly, you are calling the function run(id), not passing a handler, here is how you pass it (using anonymous function)
https://developer.mozilla.org/en/docs/DOM/element.addEventListener
div.addEventListener('mousedown',function(e){
doSomething(id);
},false);
function doSomething(id){
console.log(id);
}

Passing argument to function. What's wrong?

In this jsFiddle
am I trying to pass an argument to a function, but it doesn't receive the argument or it isn't executed.
Details
JQuery
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
Any ideas what's wrong and how to fix it?
Your function only exists within the scope of the ready event handler, you need to move function addRemove outside of the ready function.
http://jsfiddle.net/EcCTx/2/
Your code was wrapped in an onload event by jsfiddle (drop-down menu on the left). So if you add a function it won't be global, but your onclick event calls a global function by the name addRemove.
You need to define your function outside of the $(document).ready().
I haven't tested it, but my guess is this: things inside of a function can't be accessed from outside of a function. For example,
$(document).ready(function() {
function addRemove(u) {
alert(u);
}
});
console.log(addRemove); // reference error or something similar
You should define addRemove function outside of $(document).ready.
the addRemove function must be outside of $(document).ready(function(){...});
In case Davin doesn't come back, here's the answer: jsFiddle defaults to wrapping your JS in the 'onLoad' method - and we can't allow that.
http://jsfiddle.net/nqbWe/
You had no defined function called addRemove in the Fiddle!
I've added this, and removed the inline javascript calls.
See this for better way of doing it:
http://jsfiddle.net/EcCTx/6/
There is nothing specifically calling that function. In the document ready part you have the function set up, but the anchor will not call that function by itself. In this instance it will only be called when someone clicks on that link.
You could give the link a class and data attribute and use those with jQuery to have something happen on page load.

Categories