Mohan
Mohan

Reputation: 4829

How to get current object reference inside a jquery callback function?

I have a javascript Object called aObject and a fucntion inside it is used as a jQuery Callback function like this:

var aObject = {
    aVariable : 'whatever value',
    test : function(e) {
        // Trying to access property. But doesn't work as expected since I am getting the DOM element i.e form, not the aObject reference
        var temp = this.aVariable;
    }
}

$('document').ready(function(){
  $('#some-html-form').submit(aObject.test);
});

When I call the test method in aObject, this refers to the form element that has been submitted. I want to access current object from the test callback function?

I tried the below code as described in this answer but it did not work for me

$(document).ready(function() {
   $('#add_api_form').submit(api_cahce.handle_add_form_submit.bind(this));
});

Upvotes: 0

Views: 283

Answers (1)

zabusa
zabusa

Reputation: 2719

bind with aObject then you can access the variable.

var aObject = {
    aVariable : 'whatever value',
    test : function(e) {
        var temp = this.aVariable;
    }
}

$('document').ready(function(){
  $('#some-html-form').submit(aObject.test.bind(aObject));
});

Upvotes: 1

Related Questions