Weird syntax for extending jQuery - javascript

I recently saw this code on another post ( jQuery Set Cursor Position in Text Area )
new function($) {
$.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
} (jQuery);
After too long trying to understand what it was doing I finally figured out that it's just creating a new function with a parameter $ and then invoking it with jQuery as the parameter value.
So actually, it's just doing this:
jQuery.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
}
What's the reason for the original, more confusing version?

For large blocks of code using $ is much nicer than jQuery.
When using multiple libraries, people will often disable the $ shortcut because many libraries use it. Writing the code like that allows users to write code with the shortcut without worrying about conflicting with other libraries. And since this site applies to a wide audience, using that code is the most likely to work whether or not the user has $ enabled.

Since other JavaScript libraries may use $ globally, your library should explicitly reference jQuery to prevent conflicts. By creating a function with parameter $, you can bind the jQuery object to that variable within the scope of that function. This gives you the safety of explicitly specifying the jQuery object AND the convenience of using the $ shorthand.
This is the pattern I am used to seeing:
(function($) {
// code using $ goes here
})(jQuery);

new function($) {
$.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
// You are safe to always use $ here
}
} (jQuery);
and
jQuery.fn.setCursorPosition = function(pos) {
// function body omitted, not relevant to question
// you have to make sure $ was not overwritten before using it here..
}

Related

Why sometimes in Javascript there is the dollar sign ($arg) before function argument?

I see sometimes js snippets that are using the $ in front of the argument ($argName).
function someName(arg) {
// some code
// using arg
}
function someName($arg) {
// some code
// using $arg
}
In this js example it works either way with or without the $ in front of the arguments. Can anyone explaine if it has any use?
The $ character is legal in JS identifiers, and is often used simply as a code convention to indicate that the passed parameter is already a jQuery object (as opposed to a native DOM element).
This serves as a reminder that it's not necessary to re-invoke the jQuery $(param) wrapper function on that parameter.
It's also used quite a lot in Angular JS code.
It's sometimes used to reference an object from another library , like JQuery or AngularJS , what you're talking about here looks like AngularJs's dependency injection to me
UPDATE
See this answer it might be useful

Why should I reference jQuery in a self contained function?

(function ($, undefined) {
. . .
})(jQuery);
I see this everywhere, but I don't understand why we're sending jQuery as a parameter in a self contained function. jQuery is already being referenced. Also, why are we defining undefined as a parameter?
Passing $ to the anonymous function ensures that the namespace is protected (i.e. does not conflict with other libraries that also use the $ shortcut).
Oftentimes, undefined is passed to a function to ensure that the variable is truly undefined. For example, consider the following code exerpt:
undefined = '123';
if(myVar == undefined)
{
// Will only ever execute if myVar == '123'
}
As noted in the comments though, unless you're writing a plugin or some such, using jQuery(function($) { }) is probably a better approach, since it protects the $ shortcut and also provides a DOMReady event, meaning less code is required to achieve the same result.
If you need to check against undefined, you might also want to consider using $.noop().
It's possible that $ or undefined might have their values changed by subsequent code, eg. if you're mixing multiple JS libraries, or using multiple versions of a library. By capturing your own copy of $ and undefined, you guard against that.
(function ($, undefined) {
. . .
})(jQuery);
with that you'll be sure that $ is jQuery inside the function(whatever jQuery is in your script).
It doesnt prevent you from overwriting jQuery variable though,so use it only if you really need it( or you are creating a plugin and distributing a jquery plugin).
As for undefined,it will force undefined to actually be undefined,as undefined can be overwritten in some js engines.

Please explain these lines in the jQuery-ui project - has to do with adding "sub-plugins"

Lines 10 - 16 of jquery.effects.core.js:
;jQuery.effects || (function($, undefined) {
var backCompat = $.uiBackCompat !== false; // Irrelevant
$.effects = {
effect: {}
};
})(jQuery); // At end of file
As I understand it, this adds an effects "namespace", but only if it doesn't already exist.
Can someone explain to me:
What is the initial semi-colon for?
What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Edit: I realize now jQuery.effects is probably a bad example. I see jQuery.ui.core.js does it differently:
(function( $, undefined ) {
$.ui = $.ui || {};
// add some stuff to $.ui here
$.fn.extend({
// plugins go here
});
})(jQuery);
But what is the use of the ui object if plugins are added directly to $.fn anyway? Could I define my namespace under $.fn and add all my plugins to $.fn.acme, so that I use them like so: $('something').acme.doStuff()?
Is there a best practice for this sort of thing?
It checks if jQuery.effects exists
If not, it defines a function and calls in the same time
(function() { ... } (jquery), it passes jQuery object for reasons related to scope and conflict and such.
The first line in that function is said to be irrelevant, it seems to be checking a presence of a jQuery plugin property
It defines a placeholder (like namespace or container class) for the effects jQuery plugin property.
So, to your questions:
1 . What is the initial semi-colon for?
I think nothing special. Just ensuring clean statement. This has some edge cases if the last line before this one was a function declaration close.
2 . What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
It just ensures this doesn't happen later. Passes the global object directly. Common pattern I think.
3 . What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
It's the way jQuery is structured and general organization issue. The jQuery object is a function and returns an object. The .fn handles registering this one to apply on returned jQuery objects (from jQuery select or so), so, that's better so that jQuery actually knows about your added function.
4 . Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Most people don't do it. Wouldn't recommend it. Maybe a common "small" prefix is enough.

jQuery like custom functions

I have been wondering how I can create functions like jQuery. For example: $(ID).function()
Where ID is the id of an HTML element, $ is a function that return the document.getElementById reference of the element "ID" and function is a custom javascript function.
I'm creating a little library which implements some functions. And I want to use that sintax without using jQuery.
Now, my questions are: how I can implement that? What is the name of the tecnique that allow that?
Edit:
What I want to do is this:
HTMLElement.prototype.alertMe = function() {alert(this.value);}
Then, when I call document.getElementById('html_input_id').alertMe(), it must show an alertbox with the input value. But HTMLElement.prototype doesn't work in IE.
$ = function(id) {
return document.getElementById(id);
}
Okay, look, what you're asking has a lot of details and implications. The code for jQuery is open source, you can read it for the details; you'd do well to find a good Javascript book as well, the the O'Reilly Definitive Guide.
$ is just a character for names in JS, so as some of the other answers have shown, there's no reason you can't just write a function with that name:
var $ = function(args){...}
Since everyone and his brother uses that trick, you want to have a longer name as well, so you can mix things.
var EstebansLibrary = function(args){...}
var $ = EstebansLibrary; // make an alias
Since you end up doing different things with the entry point function, you need to know how JS uses arguments -- look up the arguments object.
You'll want to package this so that your internals don't pollute the namespace; you'll want some variant of the module pattern, which will make it something like
var EstebansLibrary = (function(){
// process the arguments object
// do stuff
return {
opname : implementation,...
}
})();
And you'll eventually want to be prepared for inheritance and that means putting those functions into the prototype object.
You can use prototype to assign a new function to the Element prototype.
Element.prototype.testFunction=function(str){alert(str)};
This would provide the function 'testFunction' to all HTML elements.
You can extend any base Object this way, i.e. Array, String etc.
This will work without any plugin at all - although that said I don't think it will work in IE. I believe libraries such as MooTools and jQquery create their own inheritance with DOM elements to ensure cross-browser compatibility, although don't quote me on that.

$(document).ready(function() VS $(function(){ [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
what is difference of $(function(){ }); and $(document).ready(function() { }) ;?
What are the differences between $(document).ready(function(){}) vs $(function(){})
and should I write it in the $ form or the new jQuery(document).ready(function(){ }) way?
If I have google api loaded is google.setOnLoadCallback(function() { a better way? or is it the same thing?
I've also seen people use $(function($){})
Can somebody help me, I'm lost. I bugs me when I don't know the code I write. I guess I should read through the library. Are the all being defined as the same thing?
The two ways are equivalent, I personally prefer the second, $(function() {}); it's just a shortcut for document ready.
About the new jQuery(document)... construct, you don't really need to use the new operator, jQuery will use it internally if you don't.
The argument that the ready handler function receives, is the jQuery object itself.
That's quite useful where you have to run jQuery in compatibility mode with other libraries, for example:
jQuery(function ($) {
// use $ here
});
The $ argument inside the callback will refer to the jQuery object, outside that function it might refer to another library like PrototypeJS.
$(document).ready(function() {});
$(function() {});
The two statements are actually the exact same. So the second call is just a shortcut for the first.
The $ notation is again only a shortcut for jQuery. If you have loaded jQuery into your website you can use both. Especially if you don't load other JS librarys, which maybe also use the $ sign. That brings us to your mentioned
(function($){
}(jQuery));
call. What is done here is to make sure, that within your created function expression the $ sign references to the jQuery object. You're calling that anonymous function (which has $ as parameter) and pass the jQuery object in.
I encourage to read some articles that are very useful to understand somethings in jQuery ( and of course in javascript ), this articles explain how to create a jQuery plugin, but reading it you will understand some basic and important things, like closures witch is the meaning in this (function($){}(jQuery)); statement.
http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner

Categories

Resources