Is there any reason to have nested calls to $ (jQuery)? - javascript

I was poking around the source code of a website when I came across some code like this:
$($('#newForm_step1')).hide("slide", { direction: "left" }, 0);
and this:
$($($('.breadcrumbs')[0]).children().last()).html("...");
I've never seen the $ (jQuery) function used this way, and I was wondering if there'd be any practical reason to do something like this? To the best of my knowledge, wrapping a jQuery object with a call to $ simply returns a jQuery object for the same selector, and methods on jQuery objects return this, so I don't see why one would need nested calls to $.

No, there is no reason to do this.
In the first example, $($(...)) is redundant. There is absolutely no effect in immediately wrapping a jQuery object in another jQuery object.
The line should read
$('#newForm_step1').hide("slide", { direction: "left" }, 0);
In the second example, $(...)[0] returns a raw DOM element, so it's wrapped again before having jQuery's .children().last() invoked on it. The result of that is already a jQuery object, so there is no need to re-wrap it, and the "unwrapping" could have been avoided by calling .first() instead of [0].
The line should read
$('.breadcrumbs').first().children().last().html("...");

There's no necessary to wrap jQuery object with jQuery. That will just result the same but over-coding and redundant.
But when you have DOM Object then you need to wrap with jQuery so that it will be jQuery object.
Taking your example:
$('.breadcrumbs')[0];//[0] converts to JavaScript Object
Now, if you want to work with jQuery again, you may then wrap with jQuery:
$($('.breadcrumbs')[0]);//is now a jQuery Object
But with this example is unnecessary because you can do just like this:
$('.breadcrumbs:eq(0)');//selects first .breadcrumbs element
However, if you have some DOM Object rather than jQuery object then you need jQuery wrapper to work with jQuery methods.
You must remember this:
JavaScript Object needs JavaScript methods to be chained:
javascriptObject.javascriptMethods
Ex-
$('.breadcrumbs')[0].addEventListener();//javascript addEventListener method
jQuery Object needs jQuery methods to be chained:
jQueryObject.jQueryMethods
Ex-
$('.breadcrumbs').on();//jQuery on method

Related

Automatically return jQuery object

In jQuery, when I call:
$("selector").a_function(function(){
this.toggleClass("a-class");
}
I am told that this is of a certain type, and does not have the jQuery function available to it. The problem is that I am not getting jQuery objects returned to me. The way I am getting around this is to do:
jquery_object = jQuery(this);
every time. I thought that $() is equivalent to calling jQuery and that I am supposed to receive a jQuery object.
Is this normal? What am I doing wrong here?
You'll want to use $(this) instead of just this.
In the case you gave this doesn't refer to the DOM element.
By wrapping it in the standard JQuery selector function, you'll actually be calling to the DOM element.
I use this a lot for click handlers.
$('a').click(function(e) {
$(this).toggleClass('a-class');
});
Pretty much any function in JQuery that gets called through a selector and has a callback will use this format.

Is there are similar method to .get() but one returning a jQuery object instead of a DOM one?

I was wondering if the people over at jQuery implemented an alternative method to .get(), as in one that returns a jQuery object instead of a DOM node.
This way, I don't have to
wrap the object retrieved using the .get() method with an additional $() call and
write my own jQuery plugin in order to provide that functionality.
I especially don't want to do #2 because I will pretty much be reinventing the wheel, when a functionality already exists.
you can use .eq(index), which returns a jquery instance. For example
var mycoll = $("div.myDivs")
var firstElementOfCollection = mycoll.eq(0);
or as ThiefMaster pointed out in his comment below, these will work as well (and are potentially nicer depending what you are doing :))
$("div.myDivs:eq(0)");
$("div.myDivs:first");

How does jQuery.get() work?

I'm trying to use this: http://api.jquery.com/jQuery.get/ and I don't understand why the examples look like this:
$.get("test.php");
I've never seen the syntax $.get ? Why wouldn't I do something like
$jQuery = new JQuery();
$jQuery.get(...);
The $ symbol (equivalent to jQuery) is not a constructor, it's a function and an object. As such, there is no need to use new on it.
$('css selector').get() returns an array of dom elements that the selector matched.
$.get() does an HTTP GET request
The $ variable is created by jQuery and is the same as the jQuery function / object.
You're thinking of jQuery's instance methods, which operate on jQuery objects that contain DOM elements.
$.get is essentially a static method, since it doesn't operate on a set of DOM elements.
There would be no point in calling it on a jQuery set instance, so it is called without one instead.
$ or jQuery is an object, that allows you to use some methods like get.
The new keyword is usually used with a function that acts like a class. The new keyword sets this to the variable name you assign it.
There is no reason why you would need another jQuery object (except when you want to use another libary, but there is jQuery.noConflict). All you need is in the jQuery object.
It's simple - jQuery automatically creates the variable $ pointing at at jQuery when it's first loaded.
Hence:
$.get(...);
is example the same as:
jQuery.get(...);
If you don't want $ to point at jQuery (perhaps because it's also being used by another library), look at $.noConflict()

creating a plugin return this question

it says in the documentation to allways return the this object in all cases i've seen so far you return this.each() function. So are there anyother cases other than this.each that you would return
If you are trying to add a method similar to .prev() or another such function included in jQuery, using this.map() may be useful. To answer another question on this site, I created a jQuery plugin that does exactly that.
Likewise, one might want to return a string (or other data type) from a plugin (compare .attr(), .css(), and .data()), most often from the first wrapped element when only one argument is passed to the method.
For most plugins, the main reasons to return this.each(function() { ... }) are:
Your code is executed for every DOM element referred to within the jQuery object.
It returns that same jQuery object to allow method chaining. Obviously, that doesn't apply for methods intended to return a new jQuery object, such as mine.

Understanding javascript function calls in format of myFunc(arg).something()

I'm trying to understand the format of the Javascript functions that jQuery, among other people, use.
For instance jQuery(arg).hide() or $("#obj").hide
I'd like to write similar format functions but I don't understand how.
I know how to write
function myFunc(args) {
}
but I don't understand the second part ie the .hide()
is that a function within a function?
thanks for any help
It's called method chaining. The way to achieve this is for your first function to return an object, so the second function can be called as a method on that object.
The standard way to do this style of programming is to always return the same type of object, so for example, jQuery always returns a jQuery object representing a collection of HTML nodes. If one of the calls modifies the collection then the next call will be on that collection. That's how you can do something like $('#myid').parent().hide();. $('#myid') returns a jQuery object representing the #myid element and .parent() returns a jQuery object representing the parent element of #myid. .hide() returns the same object, so you could then call another method on the same object if you wanted.
This is called method chaining. I highly recommend picking up Crockford's "JavaScript: The Good Parts". This is a very quick read but wonderfully explains OOP in JavaScript and identifies good versus bad language features. Highly recommend it.
As Skilldrick pointed out, this is called method chaining.
The most straightforward example for this is an object that returns itself when you call any of its methods:
var world = {
'hello': function() {
alert('Hello');
return this;
},
'goodbye': function() {
alert('Goodbye');
return this;
}
};
world.hello().goodbye();
This is identical to world.hello(); world.goodbye();.
jQuery does a little more than that. Calling the jQuery or $ function on a valid selector string will return a jQuery object representing the matched elements (it's not actually an array, though you could think of it as one). Most of its methods will return the object itself after modifying the object (e.g. $("a").css({...}) will apply changes to the styling of the matched elements and then return the set of matched elements again).
But some jQuery methods allow modifying the set you're working with (e.g. $("a").parent() will return a jQuery object representing the parents of the matched elements). That is, they don't return the same object, but an object that behaves identically.
You have to be careful if you decide to use this style, though, as the flow will break if you need a method that has a return value of its own (e.g. if you want calculations or getter methods). This can be avoided by passing a callback function to the method, but the resulting coding style may be terribly convoluted.

Categories

Resources