javascript call a function on event - javascript

Please explain me the difference between these two statements. which one is calling the function 'connect'. connect is a user defined function.
`peer.on('connection', connect);`
and
f.on('open', function() {
connect(f);
});

Both will call connect when the event occurs. The main difference is that the first one gets its arguments set by the event subsystem since it is called directly by whatever manages the events. If your function either doesn't use any arguments or its arguments match up exactly with what the event system passes, then the first one works fine.
In the second one, you control the arguments sent to connect(f) so you can make the arguments anything you want. So, if you want to control the arguments yourself, then the second block of code gives you that option.

There really isn't much of a difference aside from example one using a named function as the callback and the second example using an anonymous function as the callback. Named callbacks are useful if you need to reuse them or if you just want to have more control over the organization of your callbacks.
Either way, the functions will be called after the execution of 'on' is complete.
For more information about callbacks have a look at http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Related

Javascript executes function immediately when passing arguments, undesired

When I run the code:
$(".pro-tip-1").mouseover(activateProTip(1));
It calls the function activateProTip right away. It doesn't wait for the mouseover to be a true scenario.
Now if I take out the argument (1) being passed, it runs as intended. It waits for mouseover to be true then it calls the function. This is what I want, however I also want to pass an argument.
$(".pro-tip-1").mouseover(activateProTip);
The problem is I can't seem to pass an argument and have it run as intended, but I want to be able to pass an argument.
I am completely new to Javascript if that isn't already obvious so please keep your code in response simple to follow, thanks in advance!
Try this solution it will work
$(".pro-tip-1").mouseover(()=>activateProTip(1));
Explanation:
you can use always callback function for click events.
when you calling like this(activateProTip(1)), this will not binding events, that's why it will call the immediatly
This is expected, the required argument is a function. If you instead pass a statement, it will be interpreted immediately (potentially you could have called a function which actually returns a function that you want to call on mouseover!). You can instead write a function that will then call activateProTip with the argument.
$(".pro-tip-1").mouseover(() => activateProTip(1));

Can someone explain me the flow of functions in this example?

I looked at the above piece of code and tried my best to search for solutions and posted it here after giving it my all. This is my current understanding of the code:
debounce() is called when there is an input and onInput() is passed to it as a callback, and debounce function return another function , the function being returned takes an argument which is the function passed by the debounce() a.k.a the onInput() , I am stuck # func.apply(null , args);
1.Isn't func and args the same thing ????
Someone please explain step by step is possible..
debouce is only called once on the initial run, it creates and returns a new anonymous function - the actual event handler.
When the input event is triggered, the previously created function is executed and will call func (onInput) after 500ms. func is only once passed to debounce, but args are the actual input event arguments, which will be passed on to func via apply. In this case, apply is basically the same as func(...args); So func (aka onInput) will be called with the actual arguments from the input event after 500ms.
This is an example of debounce.
Debouncing is a practice which is used to improve browser performance.
A programming practice which ensure that time-consuming tasks do not fire so often.
It is used to limits the rate at which a function gets invoked.
I have explained debounce with example, please check out the link
debounce

Javascript callbacks/events

bunny.mousedown = function(mouseData){
text.setText(mouseData.global.x);
}
The 'setText' part gets called when someone presses on the bunny sprite. I'm using PIXIjs.
Hello, I'm new to JS and having a bit of a hard time understanding this code. As I understand, everything in JS is an object, including functions. In other languages that I've had experience with, you'd just use event listeners with this kind of thing.
Mousedown is a callback function, or so it says in the documentation. I think I understand what's a callback function. But, I'm confused at how it's implemented in the code above.
function display(s , callb){
alert(s);
callb(1 , 2);
}
function add(q, r){
alert((q + r).toString());
}
display("amidoindisrite?", add);
callb would be the callback function, I think... But, anyway, I don't understand how the code on the very top gets executed/called. Anyone have any ideas? What would be the equivalent in Java or Python if there is one? Thanks.
In your second example, callb is a pointer to a function, or the function definition if you like. If you apply the parentheses after it, it executes the function with the parameters provided (if any, integers 1 and 2 in this case). Other ways to execute a callback are the call() and apply() methods.
In the first example, the mousedown property expects a value that is a callback, i.e. the function definition. This example defines a function that assigned to this mousedown property. When the mousedown event is triggered for the bunny object, the mousedown property is executed (using parentheses, call() or apply(), that would depend upon the Pixjs library). That property being the function defined, the text.setText method is run.
I hope that clarifies it.

why is it necessary to wrap function call in a function body

I often see something like the following in JavaScript:
$("#sendButton").click(function() {
sendForm();
}
Why is it necessary to wrap the call to sendForm() inside a function? I would think that doing it like this would be more readable and less typing.
$("#sendButton").click(sendForm);
What are the advantages/disadvantages to each approach? thanks!
There's typically two cases where you'd want to use the former over the latter:
If you need to do any post-processing to the arguments before calling your function.
If you're calling a method on an object, the scope (this reference) will be different if you use the second form
For example:
MyClass = function(){
this.baz = 1;
};
MyClass.prototype.handle = function(){
console.log(this.baz);
};
var o = new MyClass();
$('#foo').click(o.handle);
$('#foo').click(function(){
o.handle();
});
Console output:
undefined
1
Probably one too many answers by now, but the difference between the two is the value of this, namely the scope, entering sendForm. (Also different will be the arguments.) Let me explain.
According to the JavaScript specification, calling a function like this: sendForm(); invokes the function with no context object. This is a JavaScript given.
However, when you pass a function as an argument, like this: $(...).click(sendForm), you simply pass a reference to the function for later invocation. You are not invoking that function just yet, but simply passing it around just like an object reference. You only invoke functions if the () follows them (with the exception of call and apply, discussed later). In any case, if and when someone eventually calls this function, that someone can choose what scope to call the function with.
In our case, that someone is jQuery. When you pass your function into $(...).click(), jQuery will later invoke the function and set the scope (this) to the HTML element target of the click event. You can try it: $(...).click(function() { alert(this); });, will get you a string representing a HTML element.
So if you give jQuery a reference to an anonymous function that says sendForm(), jQuery will set the scope when calling that function, and that function will then call sendForm without scope. In essence, it will clear the this. Try it: $(...).click(function() { (function() { alert(this); })(); });. Here, we have an anonymous function calling an anonymous function. We need the parentheses around the inner anonymous function so that the () applies to the function.
If instead you give jQuery a reference to the named function sendForm, jQuery will invoke this function directly and give it the scope that it promises to always give.
So the answer to your question becomes more obvious now: if you need this to point to the element target of the click when you start work in sendForm, use .click(sendForm). Otherwise, both work just as well. You probably don't need this, so skip the anonymous function.
For those curious, scope can be forced by using the JavaScript standard apply or call (see this for differences between the two). Scope is also assigned when using the dot operator, like in: obj.func, which asks of JavaScript to call a function with this pointing to obj. (So in theory you could force obj to be the scope when calling a function by doing something like: obj.foo = (reference to function); obj.foo(); delete obj.foo; but this is a pretty ugly way of using apply.
Function apply, used by jQuery to call your click handler with scope, can also force arguments on the function call, and in fact jQuery does pass arguments to its click handlers. Therefore, there is another difference between the two cases: arguments, not only scope, get lost when you call sendForm from an anonymous function and pass no parameters.
Here you are defining an anonymous event handler that could call multiple functions inline. It's dirty and tough to debug, but people do it because they are lazy and they can.
It would also work like your second example (how I define event handlers):
$("#sendButton").click(sendForm)
Something you get by defining your event handlers inline is the ability to pass event data to multiple functions and you get this scoped to the event object:
$("#sendButton").click(function(event) {
sendForm();
doSomethingElse(event);
andAnotherThing(event);
// say #sendButton is an image or has some data attributes
var myButtonSrc = $(this).attr("src");
var myData = $(this).data("someData");
});
If all you are doing is calling sendForm, then there isn't much difference, in the end, between the two examples you included.
$("#sendButton").click(function(event) {
if(event.someProperty) { /* ... */ }
else { sendForm({data: event.target, important: 'yes'}); }
}
However, in the above case, we could handle arguments passed to the callback from click(), but if the sendForm function is already equipped to handle this, then there's no reason why you wouldn't place sendForm as the callback argument if that is truly all you are doing.
function sendForm(event) {
// Do something meaningful here.
}
$("#sendButton").click(sendForm);
Note that it is up to you where you handle the differing layers of logic in your program; you may have encapsulated certain generic functionality in a sendForm function then have a sendFormCallback which you pass to these sorts of function which handle the interim business of event/callback processing before calling sendForm itself.
If you are working in a callback-heavy environment, it would be wise to separate significant functionality from the callback triggers themselves to avoid callback hell and promote maintainability and readability in your source code.
It's just to lock scope. When you wrap that sendForm() in the anonymous function that closes over the current scope. In other words, the this will be kept with it. If you just pass sendForm then any calls to this will come from the calling scope.
This is a good question for learning about scope in javascript, and questioning conventions.
Nope, that second example is perfectly valid.
99.9% of jQuery examples use the first notation, that doesn't mean you need to forget basic JavaScript syntax.

Javascript function parameters

I am working on a project which involves the ExtJS library and I came upon this piece of code which did not make sense (but it works). Please help :(.
TreePanel.on('click', showDocumentFromTree);
function showDocumentFromTree(node) {
if (TreePanel.getSelectionModel().isSelected(node)) {
dataStore.baseParams = {
node : node.id,
limit : 10
}
dataStore.load({
params : {
start : 0
}
});
}
};
So the function definition for "showDocumentFromTree" has a parameter called "node" but when the code calls it, it did not pass in anything. Also, the object "node" is not a global (as far as I know).
So I'm confused on how that works? Is this some magic that Javascript has?
Also, when I do a console.debug to print "node" it has stuff in it. (console.debug for FireBug)
Thank you for your time,
J
When the code is doing `TreePanel.on('click', showDocumentFromTree)', it isn't calling showDocumentFromTree, it's passing the function showDocumentFromTree as an argument. It will then be called later, by the onclick event handler that it's being set up for, and it will be passed its node argument then.
The first line binds the showDocumentFromTree function to the click event. What is passed to TreePanel.on is a reference to the showDocumentFromTree function, not the call itself.
When an event fires, the bound function(s) will be called, with the triggering object as the first parameter. In this case, it will be the DOM node that was clicked.
To illustrate, the first line can be rewritten to:
TreePanel.on('click', function(node) {
showDocumentFromTree(node);
});
OK, maybe this is not much clearer, but you can see that it actually passes a function as argument to the on method, rather than calling the method itself.
TreePanel is a class/component in Extjs. In your first line:
TreePanel.on('click', showDocumentFromTree);
You are assigning a click handler to the TreePanel class. Meaning, whenever the TreePanel is clicked, it will call your showDocumentFromTree function. Part of the Click Event for the TreePanel is to pass the TreeNode that initiated, or was the item, that "caused" the click event.
To see how this functionality works, look at the Ext.tree.TreeEventModel class specifically the initEvents, delegateClick, and onNodeClick functions.
In this case, the parameter to showDocumentFromTree is a magic parameter that is supplied by the browser when the user clicks on the element to which the action is attached. In this case, node will refer to the TreePanel. Javascript - The this keyword explains more detail about this mechanism. It is probably more common to use the parameter name this than node as in your example.
Wthout repeating what other posters have said about the browser supplying the arguments to the function, I wanted to make a general note about javaScript as a language. JavaScript, unlike languages like C++ and Java, does NOT respect parameters defined in the function signature. This means you can have a function like:
function doSomething(myParam){
... Does Some Stuff
}
Then call it in any manner below:
doSomething();
doSomething(foo);
doSomething(foo, bar);
doSomething(foo, bar, baz);
etc..
If it is called without parameters defined in the signature, the missing parameters will be undefined. Extra parameters can only be accessed by the args array that all functions have.
I know this wasn't specific to your question but I thought it might be good for context and general interest.

Categories

Resources