jQuery Selector Before Function - javascript

what is the difference between:
$(function () {
});
and this:
function HideDiv() {
}
i know first is jQuery Function and second is Javascript function.
but i don't know why it putted selector '$' before Function Keyword .
i thought that jQuery Selector is for finding an html Element for example this:
$("#loading").hide('fade');
finding an element with the name loading and hide that.
regards.

The $ is shorthand for jQuery, and represents the jQuery object. That context is basically a shorthand of:
jQuery(document).ready(function()
{
});
and acts as an onDOMReady function for executing code when the page has loaded. You are fundamentally "finding" the document element and running a script when it has finished loading.
The second one is just a general function

The difference is very large!
function HideDive(){
}
Creates a named function which you can later call as: HideDiv
$(function() {
});
Does something entirely other: it registers an anonymous function with jQuery, essentially saying: when the page is done loading, please call this function.
The $( ... ); notation is a shorthand which means jQuery(document).ready( ... ).
Hope this clears it up!

There are functions involved in both of those, but the context is a little different. The first:
$(function() { ... });
is both a function call and a function definition. The call is to the jQuery function itself, whose alias is "$". The function call has a parameter, and that parameter is an anonymous function. The jQuery function will respond to this function call by saving a reference to the anonymous function, and then — when the document is ready — it will call your function.
The second form is just a simple JavaScript function definition statement. It creates a function with a name that can be called by other code in the same scope, or in any lexically-enclosed scope.

The former is an anonymous function that is invoked when the DOM is ready to be interacted with by jQuery. It is analagous to:
$(document).ready(function() {
// ...
});
The latter is a named function which can be called by any code within it's scope.
Another interesting piece of function syntax is:
(function() {
// ...
})();
which is a self-executing function.

The first function (the "jQuery function") is, technically, still a JavaScript function as jQuery is just a JavaScript library. However, in this specific case, this function means something special to jQuery. Specifically, it is the ready function meaning that it will run after the DOM is ready (AKA, the page has loaded).
The second function is a "regular" function. This can be called from other portions of JavaScript code (including jQuery code, which, if you recall, is JavaScript). This allows you to encapsulate various actions or pieces of information that you may use repeatedly (rather than repeating over and over). You can combine the two, as well, like this:
$(function() {
// Call the function...
MyFunctionToDoSomething();
});
function MyFunctionToDoSomething() {
// Do stuff here.
}

The first is shorthand for $(document).ready(function(){}) [though doesn't work in after 1.4 I believe]. I can see it being easily confused with an anonymous function either way based on syntax.
A typical anonymous function would look just like your first example without the $. See Why do you need to invoke an anonymous function on the same line? for how the anonymous function works.
The second is a standard JS function (which is also an instantiatable object).

Related

Can I find a JQuery function inside some object defined into the JavaScript window global object?

I am pretty new in JavaScript and JQuery and I have the following doubt.
I know that if I open the FireBug console typing window I see the content of the global object that in a JavaScript application that run into a browser is the current browser tab (the window).
Ok, so in this global object I can see all the global variables and all the global functions (the variables and the functions that are not defined inside another function).
So I have a page in which I link my .js file.
This file will contain some pure JavaScript function like this:
function myFunction() {
.................................
.................................
.................................
}
And so I will see the myFunction function as a field of the window global object because this function is global (it is not defined inside another function). This is perfectly clear to me.
So, into the .js file linked inside my page I also have something like this:
$(document).ready(function() {
$("#myButton").click(function() {
............................................
............................................
DO SOMETHING WHEN THE BUTTON HAVING id="myButton" IS CLICKED
............................................
............................................
});
});
So, this is a JQuery code and it should work in this way (correct me if I am doing wrong assertion).
There is the $ that is the JQuery objet (or what is it?).
On this JQuery object I call the ready() function that is the function that perform its inner callback function when the DOM is completly rendered.
So the inner callback function contain the:
$("#myButton").click(function() {...DO SOMETHING...});
the select a button having id="myButton" and add to it the click event listerner that itself define an inner callback function that is performed when the button is clicked.
Is it true?
Ok...so I think that all these stuff is not direcctly in the global object because it is not directly defined into my .js file but have to be in some memory space dedicate to JQuery.
So looking inside the window object inside the FireBug console I found two objects:
$: that I think is the JQuery object...so I think that my previous custom JQuery function have to be here but I can't find it.
JQuery: that is another object that is inside the window global object.
So, my doubt is: when, inside the ready() function I declare something like
$("#myButton").click(function() {...DO SOMETHING...});
where I can find the definition of the function() {...DO SOMETHING...} inside some object defined inside the window global object? Can I find it? Or am I missing something?
jQuery stores its event-related data in a data object events applied to each element. You can use $._data() to grab this info:
$._data($('#myButton')[0], 'events')
or
$._data(document.getElementById('myButton'), 'events')
To get the callback function that you applied for your button's click listener, you can simply grab the handler. For example:
$("#myButton").click(function () { console.log('clicked'); });
var eventsInfo = $._data(document.getElementById('myButton'), 'events');
console.log(eventsInfo.click[0].handler);
The above should print out "function () { console.log('clicked'); }".
Keep in mind that there is no public documentation available for $._data(), although it is a neat thing to know!
The following blog post mentions $._data() when jQuery v1.8 was released but does warn about this:
Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.
That was back in 2012. To this day, it seems to be working fine with the latest 1.x and 2.x versions, so I don't see this going away anytime soon.
This is an anonymous function, basically a piece of unique code that you don't really want to write a named function for.
It's a one-time use-case or rather it's used to bind custom click events without littering the global object with variables.
What an anonymous function does is the exact opposite of what you are asking since you can't find it in the global object (anonymous function).
.click is a function defined in $.fn and since $ is part of the window object you could traverse there to find click e.g. window.$.fn.click would be the path to the source of $(...).click(func...) but an anonymous function is a function that gets set and then forgotten (more or less).
After all, you're not giving it a name so there is no reference it can point to which is exactly what this is.
If you use a named function as an argument to another function it's called a callback function
An anonymous function is basically a nameless callback function, a callback function is a normal function that can be passed to other functions as a callable argument - this normal function will then internally use .call() or .apply() to execute the supplied callback which is what jQuery for instance does when you bind a click
The good thing here is that you're not missing anything at all, as a matter of fact - you're asking the right question because this will look like magic if you're just starting out but once you get the hang of it it's easy to understand and use (and misuse so be careful!)
If you'd like to know how this construction works you could always build your own function that accepts a callback / anonymous function e.g.
function result_based_on_callback(a, b, fn) {
fn.call(null, a, b);
}
The above function takes two parameters and a function, it will call the function and supply the two parameters to it (the null is the context of this which is a different kind of question :))
If we were to use the above construct to do a calculation we could do so like this:
console.log(result_based_on_callback(1, 2, function(a, b) { return a + b; }));
This would return 3, you can also do this with a normal function that would otherwise take two numbers and add them - it works the same except for just passing in the function name rather than the body
like this:
function do_add(a, b) {
return a + b;
}
console.log(result_based_on_callback(1, 2, do_add));
Which will do the exact same.
I hope this allows you to understand a bit of how this works, good luck!

Anonymous functions syntax in jQuery

I have read lots of articles regarding jQuery and its syntax. However I have not fully understood its syntax and I would really like to get a better and deeper understanding of it.
Many articles fail to point out the simple syntax rules (and what they are necessary for).
As of right now I am experiencing a syntax-understanding-problem:
my HTML:
<body>
jQuery.com
jQuery.com
jQuery.com
<!-- JQUERY -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
(function ($) {
// EXAMPLE 1
$("a").each(function () {
console.log(this.title);
});
})(jQuery); // ... everything works fine.
(function ($) {
// EXAMPLE 2
$("a").each(function () {
console.log(this.title);
});
}); // ... missing (jQuery). Why isn't this working?
$(function () { // ... notice the $ at the beginning.
// EXAMPLE 3
$("a").each(function () {
console.log(this.title);
});
}); // ... missing (jQuery). Why IS this working?
// EXAMPLE 4
$("a").each(function () {
console.log(this.title);
}); // ... everything works fine.
</script>
</body>
I will clarify how I understand the code, and I would absolutely appreciate if you answer me in a very basic manner. Please do point out all my misunderstandings!
My Understanding and Questions so far:
Example 1: I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it. I pass it the jQuery-Object (with ($) but I don't know why this is important at that point). From now on my function 'speaks' jQuery (it understands its syntax - I am assuming). At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
Example 2: I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
Example 3: Now I STARTED my Javascript-function with the $ and I assume that from now on my whole function is WRAPPED inside a jQuery object. Inside this jQuery-object my function understands jQuery syntax. At the end NO (jQuery) is needed.
Example 4: Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
My Question basically is:
In Example 1, why is that ($) at the beginning AND the (jQuery) at the end necessary? What is the purpose?
I would really appreciate longer answers where I can get a deeper understanding of "reading jQuery syntax correctly" and speaking about jQuery syntax and what it requires. Thanks.
I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it.
Not quite. You create a function expression.
function () { }
You then follow it with () which calls it a moment later.
You could have done it like this:
var myfunction = function ($) { ... };
myfunction(jQuery);
I pass it the jQuery-Object (with ($) but I don't know why this is important at that point).
No. You are defining a function. It accepts a single argument, the value of which gets assigned to a local variable called $.
From now on my function 'speaks' jQuery (it understands its syntax - I am assuming).
Syntax belongs to JavaScript, not jQuery.
At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
You are passing the jQuery object for the first time. It is the argument you are passing to the function when you call it. The value of jQuery (the jQuery object) is assigned to the local $ variable.
This is used for two purposes:
It lets you use the $ variable without worrying about it being overwritten by Prototype JS, Mootools, or any of the other libraries that thought it was a good idea to use something as generic as $ as a variable name.
It lets you have local variables that won't pollute the global scope.
I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
The () are important because without them you won't call the function.
The jQuery is important because otherwise $ would be undefined within the function.
Now I STARTED my Javascript-function with the $
Here you are calling the function $() with your function expression as the argument.
$ is a horribly overloaded function that does many different things depending on what type of argument you pass it.
If you pass it a function, then it will assign that function as a document ready event handler.
When the DOM has finished loading, the event will fire and the function will be called.
Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
Yes
First off, there is no "jQuery syntax". jQuery is a library, written in JavaScript, so the syntax is JavaScript.
Example 1: I create an anonymous JavaScript-function. This function is executed right in that moment the browser reads it. I pass it the jQuery-Object (with ($) but I don't know why this is important at that point). From now on my function 'speaks' jQuery (it understands its syntax - I am assuming). At the very end of my JavaScript-function I pass it the jQuery object again (but why would that be necessary?). Please enlighten me.
You seem to know how functions and arguments work. So look at your code:
(function ($) {
// EXAMPLE 1
$("a").each(function () {
console.log(this.title);
});
})(jQuery);
You define an anonymous function that takes one argument: a variable named $, which you use in the statement $("a"). Then you call your anonymous function and pass it the jQuery object, so inside the function, $ === jQuery.
Example 2: I tried the same function without the (jQuery) at the end. Now it is not working. I understand what is missing. But why is that (jQuery) at the end so important?
Without the () at the end, you're not even calling your function. You just define it and then lose it since you're not assigning it to a variable.
If you put just (), it won't work either because the function argument $ would be undefined and override the global $ (window.$).
However, if you declared the function just as function(), I think it would work because $ would then refer to window.$.
Example 3: Now I STARTED my Javascript-function with the $ and I assume that from now on my whole function is WRAPPED inside a jQuery object. Inside this jQuery-object my function understands jQuery syntax. At the end NO (jQuery) is needed.
Now you call $ as a function with one argument: your anonymous function.
Example 4: Here I did NOT build a JavaScript function. I just use jQuery to select and return the ("a"). This code gets executed right in the second the browser reads it. No waiting for the document to be ready.
Yes you do build a function, and you pass it as argument to the each() function of the object that $("a") returns.
My Question basically is:
In Example 1, why is that ($) at the beginning AND the (jQuery) at the end necessary? What is the purpose?
What's the purpose of arguments to functions?
But what you don't seem to understand: $ is just a variable (or a function if you want, but in JS functions are variables).
The solution to your problem comes down to understanding closures within JavaScript ... and not so much jQuery - jQuery is just using closures.
With a closure you can scope the content that is within and also pass arguments to that closure for use within.
For your example 2, if you pass in jQuery to the closure it would work fine.
Like:
(function ($)
{
$("a").each(function () {
console.log(this.title);
});
})(jQuery); // arguments passed in here
Becuase you do not pass in jQuery at the end then the argument $ is undefined and therefore cannot be called in the case of $('a'). When written the way I have changed it jQuery is assigned to the $ argument, which is available to the code which is inside the closure.
Similarly for your example 3, you are not passing in jQuery and you also have no variable $ within your closure so it will not work. Note that you could change it to be like (illustrative purposes only):
(function (thisIsJquery)
{
thisIsJquery("a").each(function () {
console.log(this.title);
});
})(jQuery);
Now jQuery is assigned to the argument thisIsJquery and it is available within the closure.
As for your exmaple 4, $ is being used within the closure it was defined in (and not another closure inside that) so it is readily available for use.
Closures are an excellent way to hide implementation and provide a way to make things private in JavaScript.
Further reading:
http://www.w3schools.com/js/js_function_closures.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
I'll only focus on what's not working. The following snippet:
(function ($) {
$("a").each(function () {
console.log(this.title);
});
}) // not calling function
First of all, you're not calling the function. So, anything inside it will not run. So, you might think that by adding () at last, might solve it.
But that's not all!
Because $ refers to jQuery, outside the snippet. But since you're including a named parameter as $ and not passing anything to it, the $ inside the snippet shadows the one outside. And since it's not assigned any value, it is undefined. So you'll end up with
undefined is not a function
To prove it, adding ($) will work, as now, the named parameter $ refers to the $ which points to jQuery.

Anonymous function in javascript with jquery

What is the difference between
I know here the global jQuery is passed as $ to function,
(function($){
})(jQuery);
and this one
$(function(){
})();
The second one is not a common pattern (it will throw a type error), unless you included the invoking parentheses by mistake:
(function($){
// Normal IIFE that happens to pass jQuery in as an argument
})(jQuery);
$(function(){
// Shorthand DOM-ready event handler
}); // <-- Remove the invoking parentheses
$(function(){
// Backbone code in here
}); :
This is an alias to jQuery’s “DOMReady” function which executes when the DOM is ready to be manipulated by your JavaScript code. This allows you to write code that needs the DOM, knowing that the DOM is available and ready to be read, written to, and otherwise modified by your application.
This is not a module, though. This is only a callback function passed in to the DOMReady alias. The major difference between a module and a callback, in this case, is that jQuery waits for the DOM to be ready and then calls the callback function at the appropriate time – all from the context of jQuery – while a module pattern or immediately invoking function executes immediately after it’s defined. In the above examples, the module is receiving jQuery as a parameter, but this is not the same as using jQuery’s DOMReady event because the module function is called, passing in jQuery as a parameter, immediately. It does not wait for the DOM to be ready. It executes as soon as the function has been parsed.
(function($) {
// Backbone code in here
})(jQuery);:
This is an immediately-invoking function expression (FKA “anonymous function”, “self-invoking function”, etc).
The implementation of this is a function that is immediately invoked by the calling (jQuery) parenthesis. The purpose of passing jQuery in to the parenthesis is to provide local scoping to the global variable. This helps reduce the amount of overhead of looking up the $ variable, and allows better compression / optimization for minifiers in some cases.
In this case, the function is being used as the JavaScript “module” pattern. Modules in the currently implemented version of JavaScript in most browsers, are not specific constructs like functions. Rather, they are a pattern of implementation that use an immediately invoking function to provide scope and privacy around a “module” of related functionality. It’s common for modules to expose a public API – the “revealing module” pattern – by returning an object from the module’s function. But at times, modules are entirely self-contained and don’t provide any external methods to call.
check this
The first snipset will execute the "function($){...}" as js parser encounter it, creating a kind of private context inside it where $ argument var will point to jQuery because it is passed as argument "(jQuery)" (Useful if you want to avoid any collision with a previously declared $ var which would reference something else than the jQuery object)
The second one looks like JQuery.ready function call but with a syntax error. There is two way for writing it actualy
$(document).ready(function(){
/* DOM has loaded */
});
$(function(){
/* DOM has loaded */
});
$(function(){
});
This is just the shorthand for the DOM-ready event handler, which is the equivalent of:
$(document).ready(function(){
// execution when DOM is loaded...
});
Now over to this:
(function($){
// code here
})(jQuery);
This code will not be executed on DOM ready, but it will be executed directly. What the advantage is to pass jQuery as a parameter into the function, is to avoid collisions with the usage of the dollar symbol ($), as multiple libraries use it as a shorthand reference. Everything inside the function can safely use $, as this is being passed in as a reference to jQuery.
Read more about conflicts on the $ symbol: jQuery noConflict
If you combine the two code snippets, you get a nice and solid setup:
// $ reference is unsafe here in the global scope if you use multiple libraries
(function($){
// $ is a reference to jQuery here, passed in as argument
$(function(){
// executed on dom-ready
});
})(jQuery);
PS: Because function in JavaScript can be both a statement or an expression, depending upon context, most people add extra parenthesis around it to force it to be an expression.
(function ($)
})(jQuery);
it a function being defined and then immediately called, with the JQuery object passed in as an argument. The $ is a reference to JQuery which you can then use inside the function. It's equivalent to this:
var Test = function ($){};
Test(jQuery);
and this:
$(function (){
});
is a call to JQuery, passing in a function which it should execute once the document has finished loading.

Jquery function?

Before writing any jquery they always recommend us using
$( document ).ready(function() {});
and place all our code within this function, but I noticed certain tutorial use this instead
(function($){})(jQuery)
and
(function($){}(jQuery));
what is the difference actually?
$( document ).ready(function() { YOUR CODE });
1. This code wraps YOUR CODE in jQuery's on document ready handler. This makes sure all the HTML is loaded before you start running your script. Also, since YOUR CODE is part of an anonymous function (a closure), this keeps your global scope clean.
...
$(function(){ YOUR CODE });
2. This is the same thing as #1, just using shorthand.
...
(function($){ YOUR CODE })(jQuery)
3. This does not wrap anything in an on ready handler, so it'll run immediately, without regard to what HTML has been loaded so far. However, it does wrap YOUR CODE in an anonymous function, where you'll be able to reference the jQuery object with $.
...
(function($){ YOUR CODE }(jQuery));
4. This is the same thing as #3.
$(document).ready(function() {//when document is read
And
$(function() {
are the same thing, the second is just short hand
You can also do
$(window).load(function() {
//The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images.
(function($){})(jQuery)
is an Self-Executing Anonymous Function
So basically it’s an anonymous function that lets jQuery play nicely with other javascript libraries that might have $ variable/function. Also if you notice, all jQuery plugins code is wrapped in this anonymous function.
The first one is executing the function as soon as the document is ready while the others are IIFE's that ensures jQuery can be accessed via it's alias sign $ within that function :
var $ = 'other plugin';
(function($){
alert($); // jQuery here
})(jQuery);
The first one makes the method run on document ready. Read more here.
(function($){/*Your code*/})(jQuery)
The last two encapsulate variable / function declarations in your code to a local scope, that gets as a prameter the jQuery object. This approach is used for not littering the global scope with declarations,ie localizing variables.
The difference between the last two is just that the first one delimits function with an extra set of parentheses, to make it visually more clear.
Basically this is how modules are constructed in javascript and making sure one block of code doesn't affect the other.
For more information here's a good article about js development patterns.
Example:
var f = function (str) {
window.alert(str);
};
var name = "John Doe";
f();
Functionally is the same as
(function (w) {
var f = function (str) {
w.alert(str);
};
var name = "John Doe";
f();
})(window);
And as you can see, the first one creates variables in the global scope, that might affect other scripts, while the second one does everything locally.
Moreover in the second example I did rename the reference to window, and made it available for the method through w. The same happens in your example as well.
Imagine having two js libraries that both use the alias shorthand $. You wouldn't know in your code where, which gets referenced. While on the other hand jQuery always references the jQuery library. And in your case the last two methods just make sure that $ is just a renamed jQuery object, and not anything else coming from another library.

why is it necessary to wrap function call in a function body

I often see something like the following in JavaScript:
$("#sendButton").click(function() {
sendForm();
}
Why is it necessary to wrap the call to sendForm() inside a function? I would think that doing it like this would be more readable and less typing.
$("#sendButton").click(sendForm);
What are the advantages/disadvantages to each approach? thanks!
There's typically two cases where you'd want to use the former over the latter:
If you need to do any post-processing to the arguments before calling your function.
If you're calling a method on an object, the scope (this reference) will be different if you use the second form
For example:
MyClass = function(){
this.baz = 1;
};
MyClass.prototype.handle = function(){
console.log(this.baz);
};
var o = new MyClass();
$('#foo').click(o.handle);
$('#foo').click(function(){
o.handle();
});
Console output:
undefined
1
Probably one too many answers by now, but the difference between the two is the value of this, namely the scope, entering sendForm. (Also different will be the arguments.) Let me explain.
According to the JavaScript specification, calling a function like this: sendForm(); invokes the function with no context object. This is a JavaScript given.
However, when you pass a function as an argument, like this: $(...).click(sendForm), you simply pass a reference to the function for later invocation. You are not invoking that function just yet, but simply passing it around just like an object reference. You only invoke functions if the () follows them (with the exception of call and apply, discussed later). In any case, if and when someone eventually calls this function, that someone can choose what scope to call the function with.
In our case, that someone is jQuery. When you pass your function into $(...).click(), jQuery will later invoke the function and set the scope (this) to the HTML element target of the click event. You can try it: $(...).click(function() { alert(this); });, will get you a string representing a HTML element.
So if you give jQuery a reference to an anonymous function that says sendForm(), jQuery will set the scope when calling that function, and that function will then call sendForm without scope. In essence, it will clear the this. Try it: $(...).click(function() { (function() { alert(this); })(); });. Here, we have an anonymous function calling an anonymous function. We need the parentheses around the inner anonymous function so that the () applies to the function.
If instead you give jQuery a reference to the named function sendForm, jQuery will invoke this function directly and give it the scope that it promises to always give.
So the answer to your question becomes more obvious now: if you need this to point to the element target of the click when you start work in sendForm, use .click(sendForm). Otherwise, both work just as well. You probably don't need this, so skip the anonymous function.
For those curious, scope can be forced by using the JavaScript standard apply or call (see this for differences between the two). Scope is also assigned when using the dot operator, like in: obj.func, which asks of JavaScript to call a function with this pointing to obj. (So in theory you could force obj to be the scope when calling a function by doing something like: obj.foo = (reference to function); obj.foo(); delete obj.foo; but this is a pretty ugly way of using apply.
Function apply, used by jQuery to call your click handler with scope, can also force arguments on the function call, and in fact jQuery does pass arguments to its click handlers. Therefore, there is another difference between the two cases: arguments, not only scope, get lost when you call sendForm from an anonymous function and pass no parameters.
Here you are defining an anonymous event handler that could call multiple functions inline. It's dirty and tough to debug, but people do it because they are lazy and they can.
It would also work like your second example (how I define event handlers):
$("#sendButton").click(sendForm)
Something you get by defining your event handlers inline is the ability to pass event data to multiple functions and you get this scoped to the event object:
$("#sendButton").click(function(event) {
sendForm();
doSomethingElse(event);
andAnotherThing(event);
// say #sendButton is an image or has some data attributes
var myButtonSrc = $(this).attr("src");
var myData = $(this).data("someData");
});
If all you are doing is calling sendForm, then there isn't much difference, in the end, between the two examples you included.
$("#sendButton").click(function(event) {
if(event.someProperty) { /* ... */ }
else { sendForm({data: event.target, important: 'yes'}); }
}
However, in the above case, we could handle arguments passed to the callback from click(), but if the sendForm function is already equipped to handle this, then there's no reason why you wouldn't place sendForm as the callback argument if that is truly all you are doing.
function sendForm(event) {
// Do something meaningful here.
}
$("#sendButton").click(sendForm);
Note that it is up to you where you handle the differing layers of logic in your program; you may have encapsulated certain generic functionality in a sendForm function then have a sendFormCallback which you pass to these sorts of function which handle the interim business of event/callback processing before calling sendForm itself.
If you are working in a callback-heavy environment, it would be wise to separate significant functionality from the callback triggers themselves to avoid callback hell and promote maintainability and readability in your source code.
It's just to lock scope. When you wrap that sendForm() in the anonymous function that closes over the current scope. In other words, the this will be kept with it. If you just pass sendForm then any calls to this will come from the calling scope.
This is a good question for learning about scope in javascript, and questioning conventions.
Nope, that second example is perfectly valid.
99.9% of jQuery examples use the first notation, that doesn't mean you need to forget basic JavaScript syntax.

Categories

Resources