user1679941
user1679941

Reputation:

Can I define a variable to replace the use of $(this) in this example?

I have the following code:

$('#detailData')
    .on('click', '.gridLink', function () {
        dialog(this);
        return false;
    })

function dialog(link) {
   var $link = $(link);
   var viewURL = $link.attr('data-href')

Am I correct in saying I can replace that with this?

$('#detailData')
    .on('click', '.gridLink', function () {
        var $gridLink = $(this);
        dialog($gridLink);
        return false;
    })

function dialog($gridLink) {
   var viewURL = $gridLink.attr('data-href')

I tried to place this onto code review at stackoverflow.com. Someone needs to fix the logon problems as I just could not connect with my stack account :-(

Upvotes: 1

Views: 50

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

Yes the way you are passing in both the cases is perfectly legal.. This also has the advantage of caching it and reusing it instead of trying to access it every single time you use.

Upvotes: 1

Sampson
Sampson

Reputation: 268364

Yes, foo = $(this) is perfectly legal, and legit. In fact, it's not entirely uncommon. It's wise to do this when you feel the need to wrap this over and over in the jQuery object. This way, you wrap it once, and have a reference to work from which offers performance benefits.

Upvotes: 3

Related Questions