jQuery .on和多个范围

时间:2015-06-25 17:24:44

标签: javascript jquery oop

我在js中构建一个类,我使用jQuery.on()来做一些事情。我知道我可以使用bind来使类的范围被称为this,但这样它会替换.on()函数内当前对象的范围。我使用了var self = this的旧技巧,但它确实有效,但我想知道是否有更优雅的方式来做到这一点。

以下是我正在做的事情的一个例子:

var MyClass = function(settings){
    this.mySetting    = settings.mySetting;
    this.otherSetting = settings.otherSetting;

    this._initFunction();

};

MyClass.prototype = {
    mySetting    : '',
    otherSetting : '',

    _initFunction: function(){

        // keep a referente to the class scope
        var self = this;

        $('.selector').on( 'click', '.trigger', function(){

            if( self.mySetting == 'something' && self.otherSetting = 'some other thing'){

                // here, this is referred to '.trigger'
                $( this ).slideUp();

            }
        });
    }
}

但是,如果我这样做,代码不起作用,因为范围问题:

var MyClass = function(settings){
    this.mySetting    = settings.mySetting;
    this.otherSetting = settings.otherSetting;

    this._initFunction();

};

MyClass.prototype = {
    mySetting    : '',
    otherSetting : '',

    _initFunction: function(){

        $('.selector').on( 'click', '.trigger', function(){

            if( this.mySetting == 'something' && this.otherSetting = 'some other thing'){

                // here, this is referred to 'MyClass', so it won't work
                $( this ).slideUp();

            }
        }.bind( this ) );
    }
}

有关如何使其更优雅的任何提示,避免使用var self = this

2 个答案:

答案 0 :(得分:2)

一种方法是使用bind使this指向MyClass实例,并使用event对象获取触发事件的DOM元素。

MyClass.prototype = {
    mySetting    : '',
    otherSetting : '',

    _initFunction: function(){

        $('.selector').on( 'click', '.trigger', function (event){

            if( this.mySetting == 'something' && this.otherSetting = 'some other thing'){
                $( event.target ).slideUp();

            }
        }.bind( this ) );
    }
}

答案 1 :(得分:1)

In addition to using bind, you can use jQuery's proxy functionality to do essentially the same thing, but without worrying about old browsers' lack of support for bind.

MyClass.prototype = {
    mySetting    : '',
    otherSetting : '',

    _initFunction: function(){

        $('.selector').on( 'click', '.trigger', $.proxy(function (event){

            if( this.mySetting == 'something' && this.otherSetting = 'some other thing'){
                $( event.target ).slideUp();

            }
        }, this ) );
    }
}