Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript internal method calls when using jquery

I have a small problem with a object that uses jquery. since jquery overwrites the this pointer I cant call my sub methods without resorting to save the this pointer in a that variable is this a preferred way or is there a better solution? Is there a way to save the this pointer in the object ( like a class method with another name ) ?

Trying to learn javascript with javascript the good parts but I dont think I understand all the quirks yet :).

//from javscript the good parts
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        var F = function () {};
        F.prototype = o;
        return new F();
    };
}

var Tester = {
    printData: function (text) {
        console.log(text)
    },
    start: function () {
        var that = this;
        jQuery('id').click(function () {
             that.printData('firstColumn')
    });
  }
};

var test = Object.create(Tester)

test.start()

Best Regards Anders Olme guess this is similiar to Overwritten "this" variable problem or how to call a member function?

like image 553
Buzzzz Avatar asked Nov 13 '22 23:11

Buzzzz


1 Answers

In general, yes, that's what you have to do.

In this specific case, jQuery provides you some help.

jQuery('id')   // <-- should be #id ?
    .bind('click', { myThing : this }, function (e) {
        e.data.myThing.printData('firstColumn');
    })
;

See the docs for bind(). Internally, jQuery is just doing the exact same thing as you're doing there, so it won't make any significant difference in terms of performance, but it might make your code a bit more manageable.

like image 108
nickf Avatar answered Dec 25 '22 22:12

nickf