Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass context to bind in jQuery?

I'm inside a javascript object (vr roxx :) ), but every time I do an event bind with jQuery I have to include the main object instance's context through the data parameter in order to work with it. Isn't there an easy/neat way to do this in jQuery?

var oink = 
{
    pig: null,

    options:    
    {
        showPigMom: 0
    },

    init: function(pigObj)
    {

        //Show the pigmom
        $(this.doc).bind('keyup click', {o: this}, function(e)
        {
            var o = e.data.o;
            if (o.options.showpath)
                o.doWhatever();
        });

    ...
like image 835
Jauzsika Avatar asked Oct 12 '11 17:10

Jauzsika


2 Answers

I use the $.proxy() function

init: function(pigObj)
{
    //Show the pigmom
    $(this.doc).bind('keyup click', $.proxy(function(e) {
        if (this.options.showpath)
            this.doWhatever();
        $(e.currentTarget).text(); // use this to access the clicked element
    }, this));
}
like image 162
Karolis Avatar answered Oct 06 '22 00:10

Karolis


init: function() {
    var self = this;
    $(this.doc).bind('keyup click', function() {
        if (self.options.showpath) self.doWhatever();
    });
}
like image 35
beefyhalo Avatar answered Oct 05 '22 23:10

beefyhalo