Jquery | Function inside same function. It bad practice? - javascript

I am using this function for easiness, as I am going to use fadeTo a lot:
function fade_to(div, speed, opacity, after_fade) {
$(div).fadeTo(speed, opacity, after_fade);
}
Then I am calling the same function for after_fade parameter:
fade_to('#div', 3000, 1, function() { fade_to('#another_div', 3000, 1)});
Is that a bad thing to do? Will I have speed/smoothness issues?
Is it better to just use jQuery's default fadeTo function?
Thanks!

There is no gain to be made with your method. Plus you are using the jQuery fadeTo function. There is nothing wrong with what you did, just no gain. You could save work with such a technique if for example you had less arguments in your custom function:
function fade_to(div, after_fade) {
$(div).fadeTo(3000, 1, after_fade);
}
fade_to('#div', function(){ fade_to('#another_div', $.noop); });
This would actually save you work by preventing you from having to enter speed and opacity arguments. You could also curry it like this
function Fade_to(speed, opacity){
return function(div, callback){
$(div).fadeTo(speed, opacity, callback);
}
}
Then you could make argument saving functions on the fly like
var fade_to_foo = Fade_to(3000, 1);
fade_to_foo('#div', function(){ fade_to_foo('#another_div'); });
Otherwise there is no reason not to just write it the jQuery way
$('#div').fadeTo(3000, 1, function(){ $('#another_div').fadeTo(3000, 1); });

It's a bad practice because you cannot use any more modifiers without applying them to every instance your function is called. Since you can chain modifiers in jQuery, and most would agree that doing so is a useful feature, you are disabling that useful feature for yourself or anyone else working on this code body.
If you want to add any additional animations or stylings, you'll have to select the object again through regular jQuery this time. Extra work, extra calls, no real benefit.

this practice is against the goal of using jQuery as a chainable, short-syntax library. however if this specific functionality is useful for a project, can be effective.

Mike,
I don't know that this is necessarily a 'bad' thing to do, as it might offer easier usability or something (not sure, given that I don't know the context of your example) that using the standard function given in an API wouldn't otherwise.
Actually, having a function call itself is using an idea in CS called 'recursion' which can be useful for traversing trees (you can google both recursion, and trees to get a better idea of what I'm referring to here), or performing some kind of mathematical operation (i.e. Euclidean algorithm).
I would say, that if you're doing this, it's a great idea to ask "why". You won't be gaining anything in terms of speed since you're passing the parameters an extra time, and your function isn't accomplishing anything extra compared to the API's implementation (at least that I'm seeing). If you were to make a habit out of this...let's say with a more
computationally taxing function...you might notice a slowdown.
I'm hoping to not just answer your question here, but to give you some further insight as to why it's generally a bad idea to do this. I agree with dunsmoreb, and Thomasdotnet as well. Good points!
-sf

Your approach is convenient. I doubt it will slow down the fade effect. There is nothing wrong with this approach in my mind. If you decided that your fade effect should pulse or blink before fading you would only need to modify your function to pulse/blink and then fade all calls to fade would then run the new routine. In this case it makes sense as it reduces code and improves maintainability. Ericosg does make a valid point though why not reduce the paramaters if they are going to be the same.

It is better to just use jQuery's default fadeTo function. just this.

Related

How should I use Variables and jQuery Dom navigation?

I was just wondering which is the correct or most efficient way of navigating through the Dom using variables.
For example, can I concatenate selectors
var $container = '.my-container';
$($container).addClass('hidden');
$($container + ' .button').on('click', function(){
//something here
});
or should I use the jQuery traversal functions
var $container = $('.my-container');
$container.addClass('hidden');
$container.children('.button').on('click', function(){
//something here
});
Is there a different approach, is one best, or can you use them at different times?
The $ is usually used only when working with an actual jquery object. You generally shouldn't prefix anything with that unless it's really something from jquery.
Beyond that little bit though, performance-wise, your second bit of code is going to be faster. I made an example jsperf here: http://jsperf.com/test-jquery-select
The reason the second bit of code is faster is because (if I remember correctly) jquery caches the selection, and then any actions performed on that selection are scoped. When you use .find (which is really what you meant in your code, not .children), instead of trying to find elements through the entire document, it only tries to find them within the scope of whatever my-container is.
The time when you wouldn't want to use the second pattern is when you expect the dom to change frequently. Using a previous selection of items, while efficient, is potentially a problem if more buttons are added or removed. Granted, this isn't a problem if you're simply chaining up a few actions on an item, then discarding the selection anyway.
Besides all of that, who really wants to continuously type $(...). It's awkward.

A jQuery plugin to do multiple things to a single jQuery object?

I find myself doing different things to the same jQuery object a lot.
So instead of doing something like this:
var thing = $("pile_o_selectors");
thing.blah;
thing.blah_2;
//...
thing.blah_n;
or even worse
$("selectors").blah;
$("selectors").blah_2;
//...
$("selectors").blah_n;
So, I made a little jQuery plugin to let me do this:
$("selectors").do(function(){
this.blah;
this.blah_2;
this.blah_n;
});
Is there a built in jQuery function that already does this? Or even a plugin that already exists and is tested and mature so I don't have to put effort into making sure mine works in all cases? I tried searching the web a bit, but I don't even know what to call it.
Not 100% sure what those 'things' you want to do are, but can they simply be chained?
http://www.w3schools.com/jquery/jquery_chaining.asp
i.e. $("#p1").css("color","red").slideUp(2000).slideDown(2000);
You can just chain them. For example:
$('selector')
.hide()
.text("Hello, world!")
.fadeIn();
This works for most methods that have nothing obvious to return; in that case, they return the jQuery object again, making it possible. However, if they need to return something, then they can't return the jQuery object, and you cannot chain any further.

Is there a name for this pattern?

I am basically quite sure this pattern must exist and possess a name... for now I will call it "gate pattern"...
Here it is:
In my webpage's javascript, I have to trigger various asynchronous processes. Let's not discuss how trully async js is, but anyway I have to trigger 2 or 3 AJAX calls, must be sure, the UI build-up has finished, and so on.
Only then, when all these processes have finished, I want to do run a certain function. And precisely once.
Example
1: cropStore loaded()
2: resizeEvent()
3: productStore loaded()
The Pattern:
At the end of every (sucessful) Ajax-load-callback, the end of the GUI construction routine, etc... I set a respective flag from false to true and call gatedAction()
onEvent( 'load',
{
.... // whatever has to happen in response to cropStored, resized, etc...
// lastly:
f1 = true; //resp f2, f3, ...
gatedAction();
}
Gate will check the flags, return if any flag is still unset, only calling the target function, if all flags (or as I call them: gates) are open. If all my async pre-conditions call gatedAction() exactly once, I hope I can be sure, the actual targetFunction is called exactly once().
gatedAction ()
{
// Gate
if ( ! f1) return;
if ( ! f2) return;
if ( ! f3) return;
// actual Action ( <=> f1==f2==f3==true )
targetFunction();
}
In practice it works reliably. On a side-note: I think java-typical (not js-typical) synchronization/volatile concerns can be ignored, because javascript is not truly multithreading. Afaik a function is never stopped in the middle of it, just to grant another javascript function in the same document run-time...
So, anyone, is there a name for this? :-)
I need this pattern actually quite often, especially with complex backend UIs.. (and yes, I think, I will turn the above butt-ugly implementation into a more reusable javascript... With a gates array and a target function.)
It sounds like Balking pattern to me.
It is similar to the Rendezvous pattern, although that pattern is generally used in the context of multithreaded real-time systems.
I have no idea, if your pattern has a special name, but it seems equivalent to just using a counting semaphore, which blocks the thread, which started all those other actions, until they all made a V-invocation. Of course, there are no threads and semaphores in JavaScript, but instead of using many boolean variables you could use just one integer for counting.
In addition to the actual answer to your question, you might be interested in the Rx framework for Javascript. It's a port of the .NET version and allows you to compose events, so you don't have to work with tons of flag variables. It's meant for this sort of thing.
http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx

jQuery: is element.click(func) or element.attr('onclick','func()') more efficient?

I'm populating a list by cloning elements into it. Then I change attrs to make each item unique. They need to call a function on click, so I'm wondering if it's more efficient to use new_element.click(func); or new_element.attr('onlick','func();');
new_element.attr('onclick','func();');
Is:
inefficient (needlessly creating a new inline function from a string, that does nothing except call func and lose the this reference);
aggravating to put any complex code in, since it all has to be JS string escaped;
broken in IE, due to bugs in setAttribute.
Avoid. click()/bind('click') is there for a reason.
onclick has a number of limitations, including cluttering the DOM and only allowing one function at a time. So you should use click. See Quirks Mode for more information.
Directly referencing the function will be more efficient than having to interpret a string.
The lowest touch way of doing this, however, is this way:
$(links_selector).live('click', func);
links_selector will presumably be something like ul.listClass a.actionClass. This will not require anything to be done when new list elements get added.
Since you are using jQuery then make it this way
new_element.click(function(){
// your code
});
or you can bind the click event handler like
new_element.bind("click", function(){
// your code
});
Any difference in performance between the two is most likely going to be negligible. You should use the one that reads better, and that's element.click. (Plus, onclick has many disadvantages, as #Matthew Flaschen mentioned.)

What jQuery annoyances should I be aware of as a Prototype user?

We're considering switching our site from Prototype to jQuery. Being all-too-familiar with Prototype, I'm well aware of the things about Prototype that I find limiting or annoying.
My question for jQuery users is: After working with jQuery for a while, what do you find frustrating? Are there things about jQuery that make you think about switching (back) to Prototype?
I think the only that gets me is that when I do a selection query for a single element I have to remember that it returns an array of elements even though I know there is only one. Normally, this doesn't make any difference unless you want to interact with the element directly instead of through jQuery methods.
Probably the only real issue I've ever ran into is $(this) scope problems. For example, if you're doing a nested for loop over elements and sub elements using the built in JQuery .each() function, what does $(this) refer to? In that case it refers to the inner-most scope, as it should be, but its not always expected.
The simple solution is to just cache $(this) to a variable before drilling further into a chain:
$("li").each(function() {
// cache this
var list_item = $(this);
// get all child a tags
list_item.find("a").each(function() {
// scope of this now relates to a tags
$(this).hide("slow");
});
});
My two pain points have been the bracket hell, can get very confusing
$('.myDiv').append($('<ul />').append($('<li />').text('content')));
My other common issue has to do with the use of JSON in jQuery, I always miss the last comma,
$('.myDiv').tabs({ option1:true, options2:false(, woops)});
Finally, I've been using jQuery for about 6 months now and I don't think I'll ever go back to prototypes. I absolutely love jQuery, and a lot of the tricks they use have helped me learn a lot. one cool trick that I like is using string literals for method calls, I never really did that too much with prototypes.
$('.myDiv')[(add ? 'add' : 'remove') + 'Class']('redText');
(The only thing I can think of is that this is the element instead of a jQuery object in $("...").each(function)-calls, as $(element) is more often used then just the element. And that extremly minor thing is just about it.
Example of the above (simplified and I know that there are other much better ways to do this, I just couldn't think of a better example now):
// Make all divs that has foo=bar pink.
$("div").each(function(){
if($(this).attr("foo") == "bar"){
$(this).css("background", "pink");
}
});
each is a function that takes a function as parameter, that function is called once for each matching element. In the function passed, this refers to the actual browser DOM-element, but I find that you often will want to use some jQuery function on each element, thus having to use $(this). If this had been set to what $(this) is, you'd get shorter code, and you could still access the DOM element object using this.get(0). Now I see the reason for things being as they are, namely that writing $(this) instead of this, is hardly that cumbersome, and in case you can do what you want to do with the DOM element the way it is is faster than the way it could have been, and the other way wouldn't be faster in the case you want $(this).)
I don't think there are any real gotchas, or even any lingering annoyances. The other answers here seem to confirm this - issues are caused simply by the slightly different API and different JavaScript coding style that jQuery encourages.
I started using Prototype a couple of years ago and found it a revelation. So powerful, so elegant. After a few months I tried out jQuery and discovered what power and elegance really are. I don't remember any annoyances. Now I am back working on a project using Prototype and it feels like a step back (to be fair, we're using Prototype 1.5.1).
If you reversed the question - "What Prototype annoyances should I be aware of as a jQuery user?" - you would get a lot more answers.
Nope. Nada. Nyet.
.each:
jQuery (you need Index, even if you're not using it):
$.each(collection, function(index, item) {
item.hide();
});
Prototype (you're usually using the item, so you can omit the index):
collection.each(function(item) {
item.hide();
});
This is really only an annoyance if you're doing a lot of DOM manipulation. PrototypeJs automatically adds its API to DOM Elements, so this works in prototypejs (jQuery of course doesn't do this):
var el = document.createElement("div");
el.addClassName("hello"); // addClassName is a prototypejs method implemented on the native HTMLElement
Even without running the native element through the $() function.
PS: Should note that this doesn't work in IE.

Categories

Resources