jQuery plugin change attributes with $.extend

Asked

Viewed 130 times

5

I created an object in a plugin above .fn. Because usually they are created inside the objects from there we do the following:

(function( $ ){
    $.fn.tooltip = function(options) {

        var defaults = {
          'corDeFundo' : 'yellow'
        };

        var settings = $.extend( {}, defaults, options );

        return this.each(function() {
            $(this).css({ background: settings.corDeFundo });
        });

    }; 
})( jQuery );

But my object, was created above:

(function( $ ){
   var m = {
        "input"  : "outado",
        init:function(options){
            console.log(m.seletor);     
            return m.seletor;
        },//INIT FIM    
    }

   $.fn.input= function(method) {       

        var settings = $.extend( {}, defaults, method);

        console.log(m.seletor);
        return m.init.apply( this, arguments );


    }; 
})( jQuery );

$("div").input({
   input : "red"

})

How do I define the attributes of the object, because to catch I do so within the function: m.seletor. But to change how I have to do?

Correction: Just use it like this:

 var settings = $.extend( {}, m, method );
            console.log(settings.seletor)

My real problem is: How do I pass this object changed to the function INIT()? I’ll have to create another object, or what?

  • Hello. Where is "m.selector" not supposed to be "m.input"? If I understand correctly what you want is for the.log console to give the result of "red". That’s it?

1 answer

0

If I understand correctly, you want to use the options inside the plugin.

To illustrate I changed your code and includes the functionality of adding a new class in the element

    (function( $ ){
        $.fn.input = function(options) {
            //aqui são definidos os dados padrão
            var defaults = {
                "input"  : "outado"
            };
            //se foi passado algum item, atualiza o padrão...
            //esta variável fica disponível para todos aqui dentro
            options = $.extend(defaults, options);

            //aqui a função que vc deseja executar
            var init = function(target){
                //neste ponto podes realizar o que precisa com o seletor que foi passado como parametro
                //somente como um exemplo vou adicionar uma nova classe no item
                jQuery(target).addClass(options.input);
            };

            //inicializa...
            init(this);
        };
    })( jQuery );

to test you can

jQuery("#teste").input({input:"nova-classe"});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.