user1544337
user1544337

Reputation:

Using $(this) from within jQuery.extend()

I'm using the jQuery form plugin, and want that this plugin is used on every form.ajaxify. So I have this:

$('form.ajaxify').ajaxForm(
    // the options
);

With the HTML <form class="ajaxify" ...> ... </form>.

Now, I have some options that I want to pass always, like dataType:'json'. In addition to that, I want to be able to put more options in the form tag, like this:

<form class="ajaxify" ... data-ajaxify-options='{"target":"#x"}'> ... </form>

This is valid according to the docs on .data().

So I thought I'd use jQuery.extend(). I tried to put it like this:

$('.ajaxify').ajaxForm(
    jQuery.extend(
        {
            dataType: 'json'
        }, 
        $(this).data('ajaxify-options')
    )
);

However, this doesn't work: only the literal object is passed, and nothing is extended. I suppose this doesn't work because $(this) doesn't refer anymore to the form.ajaxify element. Is this correct? Normally one could store the $(this) in a variable, however, that would mean complicating the code, right? It wouldn't be possible on one line anymore. Or is there another solution?

Upvotes: 0

Views: 46

Answers (1)

Bergi
Bergi

Reputation: 665276

I suppose this doesn't work because $(this) doesn't refer anymore to the form.ajaxify element. Is this correct?

Yes, although this never did refer to that element. It does only inside of callback functions called by jQuery, however you are using it for building the argument to the ajaxForm call. this will refer to whatever the this context currently refers to.

Normally one could store the $(this) in a variable, however, that would mean complicating the code, right?

You would store $('form.ajaxify') in a variable, as $(this) is meaningless, but yes that's how it needs to be done. It doesn't really "complicate" the code, though:

var form = $('.ajaxify');
form.ajaxForm($.extend({
    dataType: 'json'
}, form.data('ajaxify-options')));

If you wanted to avoid the variable, you'd need to repeat the selector, which is a bad practise.

For a snippet that works for multiple forms in a selected collection, you can use .each() to apply the method on every single element with possibly different options - and in its callback, you can now use this:

$('.ajaxify').each(function() {
    // caching $this=$(this) is possible as well, but not as necessary
    $(this).ajaxForm($.extend({
        dataType: 'json'
    }, $(this).data('ajaxify-options')));
});

Upvotes: 3

Related Questions