czuk
czuk

Reputation: 6408

Reference to an object from a callback function in jQuery

I have following situation. In a constructor of a pseudo class I attach a click event to an element. When the event is triggered I would like to refer from the callback function to the object where the event was set.

Code of the pseudo class constructor

function MyClass(){
  this.myClassAttribute = "A class attribute";

  // here `this` refers to the object

  $("span").click(function(){
    // here `this` refer to a matched element, i.e. "span"
    // How to get the value of `myClassAttribute`?
  });

}

How to refer to the object without an global variable?

Upvotes: 3

Views: 4632

Answers (3)

Edu_Godoy
Edu_Godoy

Reputation: 81

I faced the same problem using jQuery $get. The call back function passed is actually a class function so you don't have access to the specific instance data.

I suppose this is a limitation of Javascript languange that does not handle object function as a call back parameter.

I solved using a similar workaround:

class customer {

    constructor() {
        this.customerName ="";
    }

    getCustomerName() {
        let dataRequest = {
            url: '/getCustomerName',
            data: {
                customerId: '035'
            },
            dataType: "json"
        };
        var thisObject = this;
        $.get(dataRequest).done(
            function(dbD) { thisObject.queryData(dbD,thisObject)}
        );
    }

    queryData(dbData,obj) {
        obj.customerName = dbData[0];
    }
}

Upvotes: 0

Stephen Delano
Stephen Delano

Reputation: 669

This is better documented in the jQuery API. jQuery Bind

$.click is just a shortcut for $.bind('click', /no data/, callback)

$('span').bind('click', { parentObj: this }, function(e) {
  var parentObj = e.data.parentObj;
  // the rest of your code goes here
}

I hope this helps!

Upvotes: 8

Kai
Kai

Reputation: 9552

In Javascript an anonymous function is able to reference all variables that existed at the scope of the function's creation. Since this gets reassigned in the callback function, you can create a local variable to store it before you enter the callback.

function MyClass(){
  this.myClassAttribute = "A class attribute";
  var myClass = this;

  $("span").click(function(){
    myClass.myClassAttribute = "hello";
  });

}

Upvotes: 14

Related Questions