javascript - jQuery .on 和多个范围

标签 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

最佳答案

一种方法是使用 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 ) );
    }
}

关于javascript - jQuery .on 和多个范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31056858/

相关文章:

javascript - 将距离字符串转换为数字

javascript - 使用 jquery 改进 json 解码

java - android 在哪里放置 OnClickListener OOP 明智的?

javascript - 表中的删除按钮,jQuery

oop - 多少个参数是一个合理的数字,大对象与原子参数。面向对象编程

php - 带条件的 PHP 类别名的替代逻辑

javascript - EmberJS调用父组件方法的方法

javascript - 使用 javascript 从 ASPX 代码隐藏页面访问类

javascript - CSS 无法识别 ID 或名称

javascript - 如何从 Base 64 字符串获取 MIME-TYPE?