Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent jquery to override "this"

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 ?

like image 249
subharb Avatar asked Dec 05 '25 19:12

subharb


2 Answers

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
        });
    };
like image 122
epascarello Avatar answered Dec 08 '25 07:12

epascarello


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
    });
};
like image 40
Selvakumar Arumugam Avatar answered Dec 08 '25 08:12

Selvakumar Arumugam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!