Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery core methods vs utility methods [closed]

jQuery methods are broadly said to be of 2 types; Core methods and Utility methods

I guess they call it $ vs $()

Could someone please provide an example of each type and highlight the differences. Thank you.

like image 434
copenndthagen Avatar asked Mar 13 '12 13:03

copenndthagen


People also ask

What is jQuery utility function?

It returns true if the first element contains the second element and returns false otherwise. jQuery.each() Unlike the each() method which iterates only over jQuery objects, the jQuery. each() utility function iterates through the elements of an array or the properties of an object.

What is $() in JavaScript?

$() The $() function is shorthand for the getElementByID method, which, as noted above, returns the ID of a specific element of an HTML DOM. It's frequently used for manipulating elements in a document. $() allows for shorter and more efficient JavaScript coding. Traditional method: document.

What is utility method in Java?

The term utility function was used by Joshua Bloch in the book Effective Java to describe the methods on classes such as Arrays, Objects and Math. The approach predates Java, and is defined by Wikipedia - Utility Class as a set of methods that perform common, often reused functions.


1 Answers

(Skip to TL; DNR at the end if you hate reading and want a summary, then go back and read the whole thing if you need what i'm saying clarified)

The Essence of jQuery

The first and often most confusing thing for people new to jQuery is what the jQuery object is, and why it works the way it does. The architecture of jQuery aims to allow developers to select and then interact with and manipulate all related elements in one statement with simple, concise syntax, and without having to worry about the pitfalls and caveats between how different browsers work. So, if I want to attach an event handler to all links on a page with a specific CSS class, I would like code that looks like $('a.my-selector').click(function() { /* my handler here */ }); rather than a monstrosity that looks at all child elements of document.body, checks to see if it's an anchor element with the my-selector class, and if so, attaches an desired handler in the way specific to that browser, and recursively calls itself for that element's children.

What's a Core Method and What's a Plugin Method

Core and Plugin methods are the same, except a core method was defined in the jQuery script, and a plugin was defined by you or another developer to extend or enhance jQuery's core functionality.

Core and Plugin methods (I'll simply refer to them as "methods" from now on) are functions that are a member of the jQuery object ($ is an alias of jQuery, to reduce typing, so $() and jQuery() are the same). These methods provide the means to traverse, interact with, and manipulate elements on a page.

How Methods Work

When you invoke $(), you create an instance of the core jQuery object, which has all the methods that have been defined thus far. Also contained in this object is a reference to all browser HTML elements that you selected, referenced, or created, depending on the argument(s) that you provided to $(). So, in a method, you should always assume you are working with a collection of elements, with zero to many items in the collection. In most cases, your method will start with something like this:

$.fn.myPlugin = function() {
  // `this` is the jquery object. the next line iterates over each element currently
  // in the collection and invokes the specified function against it.
  return this.each(function() {
     // within _this_ function, `this` is a reference to the current element
     // here, you can interact with or manipulate the element to whatever
     // ends required by your plugin.
  });
};

Note that $.fn is just an alias to the $() object's prototype. So, $.prototype and $.fn are synonymous. fn/prototype are simply JavaScript's way of letting you add or replace methods on an object.

What Should Methods Return?

Except for the exceptions I will state in a moment, a method should return the resulting jQuery object. What do I mean by resulting? If the method traverses or filters the current elements, it should return a jQuery object containing those new elements. For example: $.fn.filter takes the original elements you selected, and then removes any elements that don't match the selector you specify. Example:

$('a').filter('.my-selector'); // finds all anchor tags on the document, then removes any that don't have the class `my-selector`.

If the method only applies some behavior, then it should just return the current elements in jQuery (in this case, it's easiest to just return the results of this.each, as I demonstrated above). For example: $.fn.hide makes each selected element hidden by applying the CSS display:none, so it could just return this.each. Here's very roughly what it looks like:

$.fn.hide = function() {
   return this.each(function() {
      $(this).css({'display':'none'});
   });
}

Now, for the exceptions. You may have a method that returns a value from the elements in the collection. In that case, it is OK to not return a jQuery object, but the value. For example, $.fn.html returns the HTML content of all the selected elements as one string.

So, you may be asking, "OK, but why bother returning another jQuery object for the methods that don't return a value?". You do this so a developer can chain functionality together in one call. Going back to the .my-selector example, let's say you not only want to apply a click handler, but you also want to make the text bold.

You could say something like:

var myLinks = $('a.my-selector');

myLinks.click(function() { /* handle click */ });
myLinks.css({'font-weight':'bold'});

But, that's quite verbose, and in JavaScript, every line counts against your page weight. Since all those methods return a jQuery object, you can chain the calls in one statement:

$('a.my-selector').click(function() { /* handle click */ }).css({'font-weight':'bold'});

Much more concise, right?

Utility Functions

Utility functions are static or shared functions that wrap up oft-used functionality. They work slightly outside the normal jQuery pattern as described above, because they exist only to encapsulate some useful and reusable bit of logic. They can take in whatever parameters it needs, and return whatever it wants. For example, $.isArray is used like this:

var myArray = [];

alert($.isArray(myArray)); // displays true

It is defined roughly like this:

$.isArray = function(o) {
 // check if o is array and return true or false
};

Now, you could just as easily have just done this the "old school" JavaScript way by defining it like this:

function isArray(o) {
   // check if o is array and return true or false
}

Furthermore, you might ask what the advantage is of attaching it to $. The reason for this is to prevent overwrites of functions of the same name that have been defined by the developer, other scripts, or even other versions of jQuery (yes, you can include multiple versions of jQuery in a page if you really needed to, but that's another story).

TL; DNR

$() refers to an instance of the jQuery object, $.fn allows you to add or replace a method on the jQuery object, and $.yourFunctionNameHere lets you define a "static" or "shared" utility function to encapsulate helpful functionality that otherwise does not follow the jQuery instance pattern.

like image 110
moribvndvs Avatar answered Sep 22 '22 21:09

moribvndvs