0

I have the following:

$('.fileupload').fileupload({
    dataType: 'json',
    add: function(e, data) {
        ...
    },
    done: function(e, data) {
        ...
    }
});

What I need to do is be able to use the following between all ajax settings (add, and done):

var form = $(this).closest('form');

How would I use that variable in the function call so it can be used between all options?

user3390776
  • 61
  • 2
  • 7

1 Answers1

0

The context (this) in callbacks(add,done,..) refers to you jquery object $('.fileupload')

So :

$('.fileupload').fileupload({
    dataType: 'json',
    add: function(e, data) {
        var form = $(this).closest('form');
    //...
    },
    done: function(e, data) {
        var form = $(this).closest('form');
 //..
    }
});

UPDATE :

If you want to instantiale form jquery object only once, you must instantiate it outside then , you can use it on all callbacks(=settings)

EXAMPLE :

$('.fileupload').fileupload({
    dataType: 'json',
    add: function(e, data) {
        console.info(myForm);
    },
    done: function(e, data) {
        console.info(myForm);
    }
}).closest("form").cache('myForm') ;

Known that cache is a jquery plugin :

$.fn.cache=function(varName){var that=this;
    setTimeout(function(){window[varName]=$(that);},0);}
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • I was hoping there was a way to only call it once. – user3390776 May 10 '14 at 05:10
  • You cannot because a callback is a function which has implementation . there is no passing code between implementation – Abdennour TOUMI May 10 '14 at 05:12
  • Why the `setTimeout()`? And why pass a string that creates a global variable named `varName` that gets assigned a jQuery object referencing `window`? – cookie monster May 10 '14 at 05:22
  • it is wrong . i have update it since few sec.And don't worry about setTimeout because timeout=0 . thanks anyway – Abdennour TOUMI May 10 '14 at 05:22
  • Alright, but the global variable you're creating is still holding a jQuery object that references the `window` object. I'm not seeing the point, or the point of using `setTimeout` in the first place. – cookie monster May 10 '14 at 05:25
  • It is for reflection . I invite u to read this: http://stackoverflow.com/questions/21542060/understanding-javascript-settimeout-and-setinterval – Abdennour TOUMI May 10 '14 at 05:26
  • Look at the first comment under that question. I understand how it works. Doesn't change the fact that your global variable isn't holding the form. `setTimeout` doesn't have anything to do with reflection. I think you're not understanding how `this` works in JavaScript, or what `setTimeout` is used for. – cookie monster May 10 '14 at 05:29