How to pass extra parameter to event handling callback? - javascript

I have a button on which I want to attach an event listener. I also need to pass a extra parameter url to this function. I read about apply and I'm doing the following:
$('#list-button').on('click',postListing.apply([url]));
My problem is that as soon as this script is loaded postListing is called. I am not calling the function anywhere else. I need it to be called only on click.

The difference between bind and call/apply is that bind doesn't call the function immediately much like it loads the data with the variable when needed
You can reformat your code so it looks like this
$('#list-button').on('click', postListing.bind(this, url));

Found a way. It can be done using a closure:
var postListing = function(event, url){
return function(){
//Main functionality wrapped here
};
};
And the event listener setting remains the same:
$('#list-button').on('click',postListing.apply([url]));

Related

React JS: calling event handlers

I have started working in React recently. I noticed one behaviour like when I am trying to call my event handle with the same component like this
onClick={someEventHandler} it is triggering but when I try to do the same same like this onClick={()=> someEventHandler} it doesn't work.
I noticed that when I need to pass any arguments and calling the function like onClick={()=>someEventHandler(id)} it is working fine.
can some one explain me the logic/theory behind this?
The onClick event handler needs a function to be passed to it. Whenn the event is triggered, it calls the handler function passed to it.
In the first case it works because you pass someEventHandler to onClick which is invoked when event is fired. An invocation to the function is like someEventHandler()
Now in the second case,
onClick={()=>someEventHandler}
the function passed to onClick is ()=>someEventHandler which can be elaborated further as ()=> { return someEventHandler; }
Now if you notice above you are returning a function from the onClick event handler. The returned function is now never invoked and hence you see the above behavior
It works in the last case like onClick={()=>someEventHandler(id)}, because when the event handler is invoked, it invoked someEventHandler with id too.
However you do not need to pass id to invoke it, you can simply use it like onClick={()=>someEventHandler()} and it work, provided you don't need id as a parameter in someEventHandler.
Another thing to note when you are using function like onClick={()=>someEventHandler()} instead of onClick={someEventHandler} is that your someEventHandler will not be invoked with any arguments. If you want the event to be passed as argument to someEventHandler, you need tto explicitly pass it like
onClick={(e)=>someEventHandler(e)}
onClick={someEventHandler} will trigger the handler as soon as your component gets loaded/rendered on the screen but by adding an arrow function before the handler like this - onClick={()=> someEventHandler} will make sure not to trigger the component before you click on it

Function Call as parameter of another function on Javascript

First of all, i need this to be capabe to run on I.E. 8 at least (work requirements) and i can't use jQuery or another library to reach this.
The "issue" is that there's a function onKeyDown with a preventDefault and a function triggered onChange, which never (or randomly) executes due to prevendefault (long to explain more). I't could be solved as i'm reading onChange value and i'm setting it as onPlay, then i delete onchange attribute and the behaviour is to check if changes exists when onBlur and i'm triggering onplay event from this control function if there are changes.
Well, onPlay event (and other multimedia events) are only supported on IE 9 and up, so i need to find a way to pass through this. i can't use other events as they could be used on somewhere and could cause issues.
My idea was to send onChange value as function parameter to control function and execute it instead on triggering onplay event, but is causing me headache, it simply does nothing when i'm trying to do it.
//this is a resume of the function:
function foo(obj){
var funcioChange = toString(obj.getAttribute('onChange'));
obj.setAttribute('onBlur', 'checkChanges("'+obj.getAttribute("id")+', '+ funcioChange+'")');
obj.removeAttribute('onChange', 0);
}
When onBlur:
function checkChanges(idinput, functOnChange){
if (foo){
functOnChange;
//another things
}
}
If the function doesn't have parameter/s or you need to put it/them later in another function, you can do
foo = yourFunction;
function2 (foo){
foo(param1, param2);
}
if you have to send the params with the function call:
foo = "yourFunction(param1, param2)";
function2 (foo){
foo;
}

How to pass the event argument of jQuery .click() to a non-anonymous function

What is the proper way to accomplish the following:
$("#btn").click(function1);
Calling the function:
function function1 (event) {
event.preventDefault();
}
This seems to work, however I don't understand how function1 understands what the event argument is referring to without it being passed in. Wouldn't a listener set up like this make more sense:
$("#btn").click(function1(event));
Here is a fiddle.
The .click() function in jQuery except as first parameter a function. In Javascript function are value, as well as a primitive value or an object. Functions are first-class citizens.
If you use function1(event) as a parameter, the function will be executed, because this is the semantic of the brachet after the function name. So the .click() jQuery function will receive the output of the function, which is not the expected type.
Passing the function name as a parameter means that you are passing the function (actually, a reference to the function), not the result of the function invocation. And the function will be called when the click event will be triggered. The function in this case is called "callback".
Callbacks are very importants in Javascript, since the event-driven behaviour is the main reason for using a client-side scripting.
The concept behind the callback system is
//the click function
function doSomething(callback){
//in your case the event is the argument that jQuery will prepare for you
var argument = produceTheArgument();
//doSomething is in charge to invoke the function, passing the argument
callback(argument);
}
//your function
function myCallback(argument){
//your function will consume the argument
}
//my callback is passed as a reference, not invoked
doSomething(myCallback);
you are subscribing to event and passing a reference to the function inside click listener - the jQuery event processor will just call your function in jQuery's context and will pass all parameters to it.
In your first example function1 knows that the event variable is, because JavaScript (and subsequently jQuery) passes the event information as a parameter.
This is the nature of JavaScript, not just jQuery. Consider the following:
document.getElementById('btn').addEventListener('click', function1, false);
function function1(e)
{
console.log(e);
}
JavaScript automatically calls function1 when #btn is clicked, and it automatically adds the event information as the first parameter. jQuery simply passes this information into its own methods as well, so that you have access to it.
According to jQuery's documentation:
The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.
Reference: http://api.jquery.com/click/

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