2

I have the following class in javascript:

function User(aJid){
    this.jid = aJid;
    this.name = '';
    this.uni = '';
    this.edad = '';
    this.foto = '';
    this.avatar = '';
    this.initialize2 = function(){

        $('#edit_vcards').on('click', '#enviar_vcard', function(){
            //alert("enviando...");
            console.log(this);
        });
    };

As you can see I have a method "initialize2" that binds a function to some elements in the DOM. In there I do a console.log(this) which prints the DOM element we binded the method to and not the object that is executing the method initialize2. How can I have access to that object from that function? Its like if the scope of the function binded is the whole DOM and not the object. Anyway to do what Im trying to do ?

subharb
  • 3,374
  • 8
  • 41
  • 72

4 Answers4

10
function User(aJid){
    this.jid = aJid;
    this.name = '';
    this.uni = '';
    this.edad = '';
    this.foto = '';
    this.avatar = '';
    this.initialize2 = function(){
    var that = this;  //store a reference to maintain scope

        $('#edit_vcards').on('click', '#enviar_vcard', function(){
            //alert("enviando...");
            console.log(that);  //use that variable here
        });
    };
epascarello
  • 204,599
  • 20
  • 195
  • 236
3

Try passing the obj this to .on and the inside the handler you can use event.data to access the obj this. See below,

this.initialize2 = function(){

    $('#edit_vcards').on('click', '#enviar_vcard', {obj_this: this }, function(){
        //alert("enviando...");
        console.log(event.data.obj_this); //should be the obj this
    });
};
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0

Pass the outer this through event.data:

$('#edit_vcards').on('click', { outerThis: this }, function (event) {
    console.log(event.data.outerThis);
});
Mikael Engver
  • 4,634
  • 4
  • 46
  • 53
0

Nowadays with ES6 it can be even more elegant

$('#edit_vcards').click( () => {
            //alert("enviando...");
            console.log(this); // all your variables are availabled here
        });

or even like that (if you need only one line):

$('#edit_vcards').click( () => console.log(this) );

NOTE: This code cannot be used directly and should be additionally compiled with balel, for example.

lubart
  • 1,746
  • 3
  • 27
  • 35