S
S
schwabsergey2016-11-20 20:00:05
JavaScript
schwabsergey, 2016-11-20 20:00:05

jQuery plugin. How to access plugin options from init method in destroy method?

I'm writing a simple jQuery plugin. Its essence is to change the font color of the element on which it is installed. If an array of colors is specified, then the colors change one by one according to the timer. If the plugin has been installed, its action can be canceled by calling the appropriate method.

(function($){
    var methods = {
        init : function( options ) {
            //настройки по умолчанию
            options = $.extend({
                timerDuration: 2, //время задержки перед сменной цвета
                color: ['#c9f', '#f60', '#09f'], // массив цветов
                cycle: true // повторять изменение цветов по кругу
            }, options);

            var self = this;
            var changeColor = function () {
                var colorIndex = 0;
                var colorLength = options.color.length;
                setTimer = setTimeout(function changeColor() {
                    if($.isArray(options.color)) {
                        self.css("color", options.color[colorIndex]);
                        if (colorIndex < options.color.length - 1) {
                            colorIndex++;
                        }
                        else {
                            colorIndex = 0;
                        }
                    }
                    else{
                        self.css("color", options.color);
                    }
                    if(options.cycle === true) {
                        setTimerCycle = setTimeout(changeColor, options.timerDuration * 1000);
                    }
                    if($.isArray(options.color) && options.cycle === false) {
                        colorLength--;
                        if( colorLength > 0 ){
                            setTimerCycle = setTimeout(changeColor, options.timerDuration * 1000);
                        }
                    }
                }, options.timerDuration * 1000);
            };
           
            return this.each(changeColor);
        },

        destroy : function () {
            var self = this;
            var def = function () {
              // в этом методе нужно отменить изменения цвета и очистить таймер. Как правильно получить доступ к данным внутри метода init?
            };
            return this.each(def);
        }

    };

  jQuery.fn.changeСolor = function(method) {
      if ( methods[method] ) {
          return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
      } else if ( typeof method === 'object' || ! method ) {
          return methods.init.apply( this, arguments );
      } else {
          $.error( 'Метод с именем ' +  method + ' не существует для jQuery.changeColor' );
      }
  };

})(jQuery);

Now apply the plugin to the paragraphs:
$('p').changeColor({
    timerDuration : 5,
    color : ['red','green','blue'],
  });

And now let's cancel the plugin action:
$('p').changeColor('destroy');
Problem with the implementation of the destroy method. In it, you need to clear the timer and return the original color. Tell me how you can access the options and data of the init method in it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dark Hole, 2016-11-20
@abyrkov

Store in the object itself, in data for example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question