Why Define an Anonymous Function and Pass It Jquery as the Argument

Why define an anonymous function and pass it jQuery as the argument?

The two blocks of code you have shown are dramatically different in when and why they execute. They are not exclusive of each other. They do not serve the same purpose.

JavaScript Modules


(function($) {
// Backbone code in here
})(jQuery);

This is a "JavaScript Module" pattern, implemented with an immediately invoking function.

  • http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript
  • http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

The purpose of this code is to provide "modularity", privacy and encapsulation for your code.

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.

Immediately invoking functions are executed, well, immediately. As soon as the function definition is complete, the function is executed.

jQuery's "DOMReady" function

This is an alias to jQuery's "DOMReady" function: http://api.jquery.com/ready/


$(function(){
// Backbone code in here
});

jQuery's "DOMReady" function executes when the DOM is ready to be manipulated by your JavaScript code.

Modules vs DOMReady In Backbone Code

It's bad form to define your Backbone code inside of jQuery's DOMReady function, and potentially damaging to your application performance. This function does not get called until the DOM has loaded and is ready to be manipulated. That means you're waiting until the browser has parsed the DOM at least once before you are defining your objects.

It's a better idea to define your Backbone objects outside of a DOMReady function. I, among many others, prefer to do this inside of a JavaScript Module pattern so that I can provide encapsulation and privacy for my code. I tend to use the "Revealing Module" pattern (see the first link above) to provide access to the bits that I need outside of my module.

By defining your objects outside of the DOMReady function, and providing some way to reference them, you are allowing the browser to get a head start on processing your JavaScript, potentially speeding up the user experience. It also makes the code more flexible as you can move things around without having to worry about creating more DOMREady functions when you do move things.

You're likely going to use a DOMReady function, still, even if you define your Backbone objects somewhere else. The reason is that many Backbone apps need to manipulate the DOM in some manner. To do this, you need to wait until the DOM is ready, therefore you need to use the DOMReady function to start your application after it has been defined.

You can find plenty of examples of this around the web, but here's a very basic implementation, using both a Module and the DOMReady function:


// Define "MyApp" as a revealing module

MyApp = (function(Backbone, $){

var View = Backbone.View.extend({
// do stuff here
});

return {
init: function(){
var view = new View();
$("#some-div").html(view.render().el);
}
};

})(Backbone, jQuery);

// Run "MyApp" in DOMReady

$(function(){
MyApp.init();
});

Anonymous functions syntax in jQuery

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:

  1. 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.
  2. 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


jQuery: Why use anonymous functions as argument?

the first param to click is a callback function. A callback function is executed after the click event.

Functions in javascript are first class objects. This means they can be passed as parameters. You could pass alert to the click method. But in your second example you are not passing it, you are calling it (see Doorknob's answer)!

Where does the parameters comes from in anonymous functions of jQuery events?

If you look at the documentation at http://api.jquery.com/keypress/ you will see that the signature of the keypress method that you are using is:

.keypress( handler(eventObject) )

It clarifies below that the handler is a function. The syntax tells you that the function takes a single parameter which is an eventObject. http://api.jquery.com/category/events/event-object/ gives more details of this object.

What is the purpose of passing arguments to anonymous functions in this manner?

There is one significant difference connected also to scope. The following code:

(function(msg) { console.log(msg); })("Hello World!");​​​​​​​

is in some circumstances cleaner in terms of namespace pollution than this:

var msg = "Hello World!";
console.log(msg);

because the second code leaves variable after it is no longer needed, but may interfere with other parts of the code.

This is especially important when you execute the mentioned code outside any other function: in such case msg variable would be available everywhere on the page, as global variable.

How can I pass arguments to anonymous functions in JavaScript?

Your specific case can simply be corrected to be working:

<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>

This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.

For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there

How to pass the event argument of jQuery .click() to a non-anonymous function

The .click() function in jQuery except as first parameter a function. In Javascript function are value, as well as a primitive value or an object. Functions are first-class citizens.

If you use function1(event) as a parameter, the function will be executed, because this is the semantic of the brachet after the function name. So the .click() jQuery function will receive the output of the function, which is not the expected type.

Passing the function name as a parameter means that you are passing the function (actually, a reference to the function), not the result of the function invocation. And the function will be called when the click event will be triggered. The function in this case is called "callback".

Callbacks are very importants in Javascript, since the event-driven behaviour is the main reason for using a client-side scripting.

The concept behind the callback system is

//the click function
function doSomething(callback){
//in your case the event is the argument that jQuery will prepare for you
var argument = produceTheArgument();
//doSomething is in charge to invoke the function, passing the argument
callback(argument);
}

//your function
function myCallback(argument){
//your function will consume the argument
}

//my callback is passed as a reference, not invoked
doSomething(myCallback);

Passing parameters to Anonymous function inside click event

You don't need to pass the variables defined at the beginning as parameters, simply use it inside the function:

var div_raw_id = 'acf-download-link';
var div_id = '#' + div_raw_id;
var chapter_index = 1;
var chapter = 'chapter-' + chapter_index;

$('button[name=addnewchapter]').click(function(){
$(div_id).append('<div class="acf-input-wrap"><input id="' + div_raw_id +'" class="text" name="fields[field_55951fb44c1d6][' + chapter + '][]" value="" placeholder="" type="text"><span class="remove_btn"></span></div>');
return false;
});


Related Topics



Leave a reply



Submit