0

我已经看到了在构造函数中定义事件时有效的解决方案:

在 Javascript 中访问事件处理程序中的类成员变量

但是,当在原型中定义处理程序时,它没有范围可以从以前的解决方案中看到“var _self”。是否有适用于类似于以下代码的变体?

问题在于“幻灯片”处理程序中的“this”...指的是 HTML 元素而不是 MyView 中的成员变量。

function MyView(wrapperDiv)
{
    this.contentW = 1200;
    this.vboxW = 600;
    this.vboxH = 400;
    this.vboxX = 0;
    this.vboxY = 0;
}

MyView.prototype = {

    initHorizontalScrollBar : function ($bar)
    {
        //create the wrappers for the slider
        if($bar.find('.slider-wrap').length==0)
            $bar.append('<\div class="slider-wrap"><\div class="slider-horizontal"><\/div><\/div>');//append the necessary divs so they're only there if needed
        $bar.find('.slider-wrap').width(this.svgWidth);

        //initialize the JQueryUI slider
        $bar.find('.slider-horizontal').slider({
            orientation: 'horizontal',
            min: 0,
            max: 100,
            range:'min',
            value: 0,
            slide: function(event, ui) {

                var difference = this.contentW-this.vboxW;
                if(difference<=0)
                    return;
                this.vboxX =  (ui.value) / 100 * ( this.contentW-this.vboxW);       // 0 >= ui.value <= 100
                this.svg.setAttribute("viewBox", toViewBoxString(this.vboxX, this.vboxY, this.vboxW, this.vboxH));
                $('ui-slider-range').width(ui.value+'%');//set the height of the range element
            }
          });     


        this.sizeHScrollbar();
    }
};
4

1 回答 1

1

您只需要在 initHorizo​​ntalScrollBar 方法中添加一个包含正确引用的变量:

MyView.prototype = {

    initHorizontalScrollBar : function ($bar)
    {
        var _self = this;
        //create the wrappers for the slider
        if($bar.find('.slider-wrap').length==0)
            $bar.append('<\div class="slider-wrap"><\div class="slider-horizontal"><\/div><\/div>');//append the necessary divs so they're only there if needed
        $bar.find('.slider-wrap').width(this.svgWidth);

        //initialize the JQueryUI slider
        $bar.find('.slider-horizontal').slider({
            orientation: 'horizontal',
            min: 0,
            max: 100,
            range:'min',
            value: 0,
            slide: function(event, ui) {

                var difference = _self.contentW - _self.vboxW;
                if(difference<=0)
                    return;
                _self.vboxX =  (ui.value) / 100 * ( _self.contentW - _self.vboxW);       // 0 >= ui.value <= 100
                this.svg.setAttribute("viewBox", toViewBoxString(_self.vboxX, _self.vboxY, _self.vboxW, _self.vboxH));
                $('ui-slider-range').width(ui.value+'%');//set the height of the range element
            }
          });     


        this.sizeHScrollbar();
    }
};
于 2013-02-18T21:29:24.037 回答