3

I'm trying to create multiple instances of a slider on a page. Each slider should know which slide it’s currently viewing. It seems that when I update the slide property, I change it for the class, and not the instance. This suggests to me that I'm not instantiating properly in my public init() function. Where am I going wrong?

var MySlider = (function() {

    'use strict';

    var animating = 0,
           slides = 0, // total slides
           slider = null,
            slide = 0, // current slide
             left = 0;

    function slideNext(e) {
        if ((slide === slides - 1) || animating) return;

        var slider = e.target.parentNode.children[0],
                 x = parseFloat(slider.style.left);

        animate(slider, "left", "px", x, x - 960, 800);
        slide++;
    }

    return {
        init: function() {
            var sliders = document.querySelectorAll('.my-slider'),
                      l = sliders.length;

            for (var i = 0; i < l; i++) {
                sliders[i] = MySlider; // I don't think this is correct.

                slider = sliders[i];

                buildSlider(slider);

            }
        }
    }

})();
4

2 回答 2

5

根据您的评论,我认为这更像您想要的:

MySlider = (function () {
    Slider = function (e) {
        this.e = e;
        // other per element/per slider specific stuff
    }

    ...

    var sliders; // define this out here so we know its local to the module not init

    return {
        init: function () {

            sliders = document.querySelectorAll('.my-slider');
            var l = sliders.length;

            for (var i = 0; i < l; i++) {
                sliders[i] = new Slider(sliders[i]); //except I'd use a different array

                slider = sliders[i];

                buildSlider(slider);
        }
    }
})();

这样,您将每个元素与它自己的元素特定数据相关联,但是您有一个包含模块,您可以在其中对您的模块集合进行操作。

于 2013-04-24T14:57:00.063 回答
3

似乎当我更新幻灯片属性时,我为类而不是实例更改它。

你是对的。该代码仅在定义 MySlider 类时运行。如果你想要一个实例变量,你需要在返回的对象中声明它,即你的返回块的一部分:

 var MySlider = (function(param) {
    return {
       slider: param, 

       init: function() {
            var sliders = document.querySelectorAll('.my-slider'),
                      l = sliders.length;

            for (var i = 0; i < l; i++) {
                sliders[i] = MySlider; // I don't think this is correct.

                slider = sliders[i];

                buildSlider(slider);

            }
        }
});
于 2013-04-24T14:22:55.420 回答