AdityaParab
AdityaParab

Reputation: 7100

jQuery - What is the difference

I was examining one of my client's code and came across this.

$(document).ready(function() {
    function foo1() {
        $("#id1").bind('click', function() {});
    }
    foo1();

    function foo2() {
        $("#id2").bind('click', function() {});
    }
    foo2();
});

What they are doing is, attaching event handler inside the function and then calling that function.

How does it differ from the following?

$(document).ready(function() {
    $("#id1").bind('click', function() {});
    $("#id2").bind('click', function() {});
});

That is attaching event handlers directly in $(document).ready() function.

It works fine in both the scenarios, I was just wondering if there are some performance related issues or something. Like one works faster or slower. Or is it a standard way of doing things which I am not aware of.

Upvotes: 2

Views: 96

Answers (1)

Ronn0
Ronn0

Reputation: 2259

The difference it you can re-use that part of your code to call foo2() at any place in your code again instead of copy the whole code.

EDIT:

Let me give you an example

On failure it needs to show an alert with 'Hello, that was going wrong!' you can do these two things:

alert('Hello, that was going wrong!');

or

function showError() {
alert('Hello, that was going wrong!');
} 
showError();

Solution 1 seems to be the easiest one.

But..... Imagine you are working on a really large project with places to show that error on 1000 places. Now you need to edit your message at 1000 places instead of just one place.

Or when you want to show an HTML popup instead of an alert, imagine changing that.

Hopes the explanation it makes sense, when not please let me know.

Upvotes: 1

Related Questions