有没有办法在jQuery中传递上下文绑定?

Jau*_*ika 18 javascript jquery

我在一个javascript对象(vr roxx :))中,但每次我使用jQuery进行事件绑定时,我必须通过data参数包含主对象实例的上下文才能使用它.在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();
        });

    ...
Run Code Online (Sandbox Code Playgroud)

Kar*_*lis 23

我用的是这个$.proxy()功能

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));
}
Run Code Online (Sandbox Code Playgroud)