Is there any difference between the following: (Is there any reason to avoid example One?)
One:
$("#stuff").on("resize", function() { doThis(); });
$("#stuff").on("resize", function() { doThat(); });
Two:
$("#stuff").on("resize", function() {
doThis();
doThat();
});
Straightforwardly, there's no real difference.
In real-world code,
You may need to attach the two handlers in different places in your code, in which case you have to use version One (or similar).
You may want the ability to selectively detach handlers, in which case, the event can be namespaced as follows:
Attach handlers:
$("#stuff").on("resize.A", function() { doThis(); });
...
$("#stuff").on("resize.B", function() { doThat(); });
Detach one handler:
$("#stuff").off("resize.A");
The handler for resize.B remains attached (ie. doThis() will not be called but doThat() will be called) .
In your second example, if doThis() throws an exception then doThat() won't run. Not the case with the first example.
The only difference is that two distinct event handler functions are stored and executed wheres the second snippet is satisfied with one.
Do the math, second snippet is more elegant. I won't start talking about performance, but if we would bind like "hundreds" of methods that way, it becomes obvious that you don't want to bind multiple handlers.
The second will be a little more performant.
In the first example, you have the overhead of two function calls when the resize event fires (in addition to the calls to doThis and doThat). In the second example, you only have one event handler being called.
Related
In javascript we have addEventlister, this listens to an even and calls a function called a listener function. Is an alternate approach possible where we increment the value of a "let variable" without using a function to do this in case of event being triggered?
Instead of this
let clickVar = 0;
x.addEventListener("click", RespondClick);
function RespondClick() {
clickVar++;
}
Sample Alternate implementation
x.addEventListner(click);
if (event == true){ clickVar++; }
======Edit======
Responding to the comment
The more I read this, the more it seems like an XY problem - is there something else you are trying to solve?`
In my view, the second approach is more intuitive. i.e. why create a function unless it's absolutely necessary.
Responding to the comment
There is no logic to how the second approach. The code you write will be executed once. If you want to run code more than once, you have to call a function. In order to run a function when an event happens, you need an event listener.
This simple amendment should take care of the one-time calling problem.
x.addEventListner(click);
if (event == true){ clickVar++; event=false; }
But the point I am trying to make is function could have been avoided, the code could be easy enough to speak, not only write.
Your second sample doesn't work. That simply isn't how event listeners work. You must use a callback function. If you think the first sample is too verbose, you can use an anonymous function:
let clickVar = 0;
x.addEventListener("click", function() {
clickVar++;
});
Or an arrow function in more modern versions of Javascript
x.addEventListener("click", () => {
clickVar++;
});
I have this code:
$('#email').keyup(function() {
if(true || false)) {
} else {
}
});
I need include this function also in blur event.
I've tried to create a jquery function but I could not. Somebody give me a light.
You can do this -
$('#email').on('keyup blur',function() {
http://api.jquery.com/on/
Use the on method to attach multiple events, which are specified in the first argument passed to the function.
$('#email').on('keyup blur', function() {
if(true || false) { //there was an extra ) here
} else {
}
});
Working Example http://jsfiddle.net/nv39M/
One thing to be aware of, the keyup event is going to fire prior to the blur event firing.
Make a separate function as follows
function funcName(){
//Your code
}
Now,use jQuery on
$("#email").on("keyup",funcName);
$("#email").on("blur",funcName);
For reference,check
http://api.jquery.com/on/
There are (at least) two ways you could achieve this.
Specify multiple, space separated events as the first argument:
$('#email').on('keyup blur',function() {
// your logic
});
Use a named function:
function yourFunction() {
// your logic
}
$('#email').on('keyup', yourFunction);
$('#email').on('blur', yourFunction);
Option 1 is probably the best choice assuming you don't want to use the function anywhere else, and that you want to bind the event handlers at the same time. If, however, you wanted to bind the blur event at a later point (perhaps in response to another event), or to a different element, then the named function method would be the best choice.
I'm trying to understand what the differences are (if any) between these 2 ways of calling JavaScript/jQuery functions.
Method 1, in document.ready():
$('body').on('click', 'a.popup', popup);
then
function popup() {
$(this) // do something
}
Method 2, in document.ready():
popup();
then
function popup() {
$("a.popup").click(function (e) {
// do something here
});
}
All advice appreciated.
In method 2, the popup function is likely to be called only once, otherwise you attach the same function onclick several times, which propably is not what you want.
Therefore there is no great benefit in writing the popup function's body elsewhere than directly in document.ready().
Advantage of method 1 is if you want to attach the same function to various events and/or various elements, e.g. onclick, onmousemove etc. This way you won't have to write the function's body twice.
In short, i don't see benefits in method 2, whereas i see some in method 1.
I'm not quite sure, but I think you're asking what the difference between calling the jQuery .on() method and the jQuery .click() method, right?
As in:
$someEl.on('click', someFunc);
// or
$someEl.click(someFunc);
Like this, both are pretty much equivalent. However with the .on() method you have the opportunity to introduce namespacing (explained in the first link) to your element's events. Like so:
$someEl.on('click.do1', someFunc1);
$someEl.on('click.do2', someFunc2);
So if in a later progress you want to remove or trigger only one of your callback functions (someFunc1, someFunc2), you'll be able to do so by calling:
$someEl.off('click.do1');
$someEl.trigger('click.do2');
Hope this helps
I have a situation where I need to use jQuery's $.fn.one() function for a click event, but I don't want it to apply to the next occurrence of the event (like it usually does), I want it to apply to the occurrence immediately after that, and then unbind itself (like .one() normally does).
The reason I don't want .one() to apply to the first occurrence is because I'm binding to the document from an event handler invoked earlier in the bubbling phase, so the first time it gets to document it'll be part of the same event. I want to know when the very next click event occurs.
Note: I do not want to use .stopPropagation() because it will potentially break other parts of my app.
Here are the two options I've come up with, though it seems like there must be a more elegant solution.
The double bind method:
$(document).one('click', function() {
$(document).one('click', callback);
});
The setTimeout method:
setTimeout(function() {
$(document).one('click', callback);
}, 1);
Both methods work just fine, but here's my question. I have no idea what the performance implications are for either setTimeout or frequent event binding and unbinding. If anyone knows, I'd love to hear it. But more importantly, I'd like some suggestions on how to measure this stuff myself for future situations like this.
I love sites like http://jsperf.com, but I don't know if it would really be helpful for measuring stuff like this.
And obviously, if someone sees a much better solution, I've love to hear it.
I find the double-bind method quite elegant - I think it accurately reflects your actual intent, and it only takes two lines of code.
But another approach is rather than using .one() you could use .on() and update the event object associated with the first event, adding a flag so that the callback will ignore the first time it is called:
function oneCallback(e) {
if (e.originalEvent.firstTimeIn)
return;
alert("This is the one after the current event");
$(document).off("click", oneCallback);
}
$("div.source").click(function(e) {
e.originalEvent.firstTimeIn = true;
$(document).on("click", oneCallback);
});
Demo: http://jsfiddle.net/q5LG4/
EDIT: To address your concerns about not modifying the event object (or any object you don't own) you could store a firstTime flag in a closure. Here's a rather dodgy .oneAfterThis() plugin that takes that approach:
jQuery.fn.oneAfterThis = function(eventName, callback) {
this.each(function() {
var first = true;
function cb() {
if(first){
first = false;
return;
}
callback.apply(this,[].slice.call(arguments));
$(this).off(eventName,cb);
}
$(this).on(eventName, cb);
});
};
$(someseletor).oneAfterThis("click", function() { ... });
I'm sure that could've done that more elegantly (perhaps I should've bothered to look at how jQuery implements .one()), but I just wanted to whip something up quickly as a proof of concept.
Demo: http://jsfiddle.net/q5LG4/1/
I read the following on the web this weekend and I wanted to know if most others consider this the right (better) way of doing things.
This is not the best (right) way to do things:
$(document).ready(function() {
$('#magic').click(function(e) {
$('#yayeffects').slideUp(function() {
// ...
});
});
$('#happiness').load(url + ' #unicorns', function() {
// ...
});
});
That this is better:
var PI = {
onReady : function() {
$('#magic').click(PI.candyMtn);
$('#happiness').load(PI.url + ' #unicorns', PI.unicornCb);
},
candyMtn : function(e) {
$('#yayeffects').slideUp(PI.slideCb);
},
slideCb : function() { ... },
unicornCb : function() { ... }
};
$(document).ready(PI.onReady);
Does one perform better than the next? Easier for debugging?
Thoughts? Comments?
If you have a stacktrace with lots of anonymous functions in it it takes significantly more time to find out where the error exactly has happened and from where it was called. so plus 1 for second.
The code inside an event handler has often not much to do with the code where the handler gets registered and should therefore be in a separate function/module. plus 1 for second.
Using anonymous functions for listeners is also bad because in case you have to remove this listeners (which most people don't care about) you can remove only them and you don't have to care about accidentally removing other listeners form other parts of code. plus 1 for the second.
Put the related functions into a single object is not necessarily the best. Mostly the onReady function is bad if you use the behaviour of the listeners for different dom objects.
don't care about performance. a listener is usually not called that often that it matters.If it does, there is most likely a problem somewhere else.
The second variant is reusable - you can reuse slideCb and other handlers for other events for other controls.