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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7743835/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:08:47  来源:igfitidea点击:

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

javascriptjquery

提问by Jauzsika

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?

我在一个 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();
        });

    ...

回答by Karolis

I use the $.proxy()function

我用这个$.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));
}

回答by beefyhalo

init: function() {
    var self = this;
    $(this.doc).bind('keyup click', function() {
        if (self.options.showpath) self.doWhatever();
    });
}

回答by Max Podriezov

init: function() {
    $(this.doc).bind('keyup click', function() {
       if (this.options.showpath) this.doWhatever();
       $(e.currentTarget).text(); // use this to access the clicked element
    }.bind(this))
}