Как установить плагин jquery один раз? - PullRequest
0 голосов
/ 30 ноября 2009

Я работаю с подключением jQuery, и у меня есть одна ошибка, я хочу изменить опцию одного экземпляра плагина, но когда я пытаюсь это сделать, я меняю опции всех экземпляров. Хорошо, мой английский ужасен, так что лучше, чем я положил свой код. Это универсальный язык ...

(функция ($) {

$.fn.interruptor = function(options){
    // Variable iniciales
    var esMetodo = (typeof options == 'string'),
            args = Array.prototype.slice.call(arguments, 1),
            returnValue = this;

    // Previene la llamada a los métodos internos       
    if(esMetodo && options.substring(0, 1) == '_') return returnValue;

    (esMetodo)
        ? this.each(function(){
            var instance = $.data(this, 'interruptor');
            console.dir(instance);
            return ($.isFunction(instance[options])) ? instance[options].apply(instance, args) : returnValue;
        })
        : this.each(function(){
            ($.data(this, 'interruptor') 
                || $.data(this, 'interruptor', new $.interruptor(this, options))._init());
        });

        return returnValue;
} // fin $.fn.interruptor

$.interruptor = function(elem, options){
    this.config = $.extend(true, $.fn.interruptor.defaults, {numero: parseInt(Math.random()*100)}, options);
    this.id = $(elem).attr('id');
};

$.interruptor.prototype = {
    _init: function(){
        console.info(this.config.numero);
    },
    setter: function(k, v){
        this.config[k] = v;
        return false;
    },
    getter: function(){
        return this.id;
    },
    debug: function(msg){
        console.info(msg);
        console.dir(this.config);
    }
};


//Definición de los valores por defecto.
$.fn.interruptor.defaults = {
        numero: 0,
        img:            'images/iphone_switch_square2.png',     // Dirección base en la que se encuentra la imagen que genera el interruptor
        estado:     true,                                                               // 0 => OFF, 1 => ON 
        deshabilitado: false,                                                       // Indica si el plugin se encuentra actualmente deshabilitado
        duracion: 200,                                                                  // Duración en milisegundos del cambio de estado
        funcionOn : function(){alert ('On');},                  // Definimos la función que se ejecuta en el On
        funcionOff : function(){alert ('Off');}                 // Definimos la función que se ejecuta en el Off
};})(jQuery);

Пожалуйста, любой может мне помочь.

Thx

1 Ответ

0 голосов
/ 30 ноября 2009

Хорошо, просто ответьте на вопрос ... У меня ошибка в моем коде:

эта строка кода неверна

this.config = $ .extend (true, $ .fn.interruptor.defaults, options);

правильная строка включает пустой словарь:

this.config = $ .extend (true, {}, $ .fn.interruptor.defaults, options);

Так что мне нужно инициализировать структуру. Хорошо, это фиктивная ошибка, извините.

Ладно, теперь я могу установить параметры моего плагина один раз.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...