Answer the question
In order to leave comments, you need to log in
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);
$('p').changeColor({
timerDuration : 5,
color : ['red','green','blue'],
});
$('p').changeColor('destroy');
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question