2

我正在尝试构建一个自动实例化 jquery ui 滑块的类。我已经可以实例化滑块,让它们运行等。但是当我绑定幻灯片事件时,我遇到了this现在事件的问题。我已经var _self = this;解决了这个问题,但它会被类的每个实例覆盖。

班上:

$(function(window){
    function WoningSelector(slider_id, min_id, max_id, step, min, max){
        this.initialize(slider_id, min_id, max_id, step, min, max);
    }
    WoningSelector.prototype = {};
    var _self;

    // Constructor
    WoningSelector.prototype.initialize = function(slider_id, min_id, max_id, step, min, max){
        this.slider = $('#' + slider_id);
        this.min = $('#' + min_id);
        this.max = $('#' + max_id);

        this.iMin = min;
        this.iMax = max;
        this.step = step;

        _self = this;
        _self.slider.slider({
            range: true,
            step: this.step,
            min: this.iMin,
            max: this.iMax,
            values: [(this.iMin + (this.step * 4)), (this.iMax - (this.step * 4))],
            slide: this.slide
        });

        _self.min.text(this.iMin + (this.step * 4));
        _self.max.text(this.iMax - (this.step * 4));
    };

    // Slide event handler
    WoningSelector.prototype.slide = function(event, ui){
        _self.min.text(ui.values[0]);
        _self.max.text(ui.values[1]);
    };

    window.WoningSelector = WoningSelector;
}(window));
4

1 回答 1

1

在事件处理程序中使用“this”(删除self),但是在绑定到事件时,不要简单地传递

WoningSelector.prototype.slide

而是通过

$.proxy(WoningSelector.prototype.slide, theConcreteInstanceYouBind)

这样,您的处理程序将被调用,上下文 (this) 为 theConcreteInstanceYouBind。

于 2013-06-19T12:31:29.980 回答