Pergunta

Estou tentando escrever um plugin jQuery que fornecerá funções/métodos adicionais ao objeto que o chama.Todos os tutoriais que li online (estou navegando nas últimas 2 horas) incluem, no máximo, como adicionar opções, mas não funções adicionais.

Aqui está o que estou procurando fazer:

//formata div para ser um contêiner de mensagens chamando o plugin para essa div

$("#mydiv").messagePlugin();
$("#mydiv").messagePlugin().saySomething("hello");

Ou algo nesse sentido.Aqui está o que tudo se resume a:Eu chamo o plugin e depois chamo uma função associada a esse plugin.Não consigo encontrar uma maneira de fazer isso e já vi muitos plug-ins fazerem isso antes.

Aqui está o que tenho até agora para o plugin:

jQuery.fn.messagePlugin = function() {
  return this.each(function(){
    alert(this);
  });

  //i tried to do this, but it does not seem to work
  jQuery.fn.messagePlugin.saySomething = function(message){
    $(this).html(message);
  }
};

Como posso conseguir algo assim?

Obrigado!


Atualização em 18 de novembro de 2013:Alterei a resposta correta para os seguintes comentários e votos positivos de Hari.

Foi útil?

Solução

De acordo com a página de autoria de plug -in jQuery (http://docs.jquery.com/plugins/authoring), é melhor não enlamear os namespaces jQuery e jQuery.fn. Eles sugerem este método:

(function( $ ){

    var methods = {
        init : function(options) {

        },
        show : function( ) {    },// IS
        hide : function( ) {  },// GOOD
        update : function( content ) {  }// !!!
    };

    $.fn.tooltip = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            // Default to "init"
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  methodOrOptions + ' does not exist on jQuery.tooltip' );
        }    
    };


})( jQuery );

Basicamente, você armazena suas funções em uma matriz (escopo para a função de embalagem) e verifica uma entrada se o parâmetro passado for uma string, revertendo para um método padrão ("init" aqui) se o parâmetro for um objeto (ou nulo).

Então você pode chamar os métodos como assim ...

$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method
  foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

A variável JavaScripts "Argumentos" é uma matriz de todos os argumentos aprovados, para que funcione com os parâmetros arbitrários dos parâmetros de função.

Outras dicas

Aqui está o padrão que usei para criar plugins com métodos adicionais. Você usaria como:

$('selector').myplugin( { key: 'value' } );

ou, para invocar um método diretamente,

$('selector').myplugin( 'mymethod1', 'argument' );

Exemplo:

;(function($) {

    $.fn.extend({
        myplugin: function(options,arg) {
            if (options && typeof(options) == 'object') {
                options = $.extend( {}, $.myplugin.defaults, options );
            }

            // this creates a plugin for each element in
            // the selector or runs the function once per
            // selector.  To have it do so for just the
            // first element (once), return false after
            // creating the plugin to stop the each iteration 
            this.each(function() {
                new $.myplugin(this, options, arg );
            });
            return;
        }
    });

    $.myplugin = function( elem, options, arg ) {

        if (options && typeof(options) == 'string') {
           if (options == 'mymethod1') {
               myplugin_method1( arg );
           }
           else if (options == 'mymethod2') {
               myplugin_method2( arg );
           }
           return;
        }

        ...normal plugin actions...

        function myplugin_method1(arg)
        {
            ...do method1 with this and arg
        }

        function myplugin_method2(arg)
        {
            ...do method2 with this and arg
        }

    };

    $.myplugin.defaults = {
       ...
    };

})(jQuery);

Que tal essa abordagem:

jQuery.fn.messagePlugin = function(){
    var selectedObjects = this;
    return {
             saySomething : function(message){
                              $(selectedObjects).each(function(){
                                $(this).html(message);
                              });
                              return selectedObjects; // Preserve the jQuery chainability 
                            },
             anotherAction : function(){
                               //...
                               return selectedObjects;
                             }
           };
}
// Usage:
$('p').messagePlugin().saySomething('I am a Paragraph').css('color', 'red');

Os objetos selecionados são armazenados no fechamento do MessagePlugin, e essa função retorna um objeto que contém as funções associadas ao plug -in. Em cada função, você pode executar as ações desejadas com os objetos atualmente selecionados.

Você pode testar e brincar com o código aqui.

Editar: Código atualizado para preservar o poder da cadeia de jQuery.

O problema com a resposta atualmente selecionada é que você não está realmente criando uma nova instância do plugin personalizado para todos os elementos do seletor como você pensa que está fazendo ... na verdade, você está apenas criando uma única instância e passando o próprio seletor como o escopo.

Visão Este violino Para uma explicação mais profunda.

Em vez disso, você precisará percorrer o seletor usando jQuery.Each e instanciar uma nova instância do plug -in personalizada para cada elemento do seletor.

Aqui está como:

(function($) {

    var CustomPlugin = function($el, options) {

        this._defaults = {
            randomizer: Math.random()
        };

        this._options = $.extend(true, {}, this._defaults, options);

        this.options = function(options) {
            return (options) ?
                $.extend(true, this._options, options) :
                this._options;
        };

        this.move = function() {
            $el.css('margin-left', this._options.randomizer * 100);
        };

    };

    $.fn.customPlugin = function(methodOrOptions) {

        var method = (typeof methodOrOptions === 'string') ? methodOrOptions : undefined;

        if (method) {
            var customPlugins = [];

            function getCustomPlugin() {
                var $el          = $(this);
                var customPlugin = $el.data('customPlugin');

                customPlugins.push(customPlugin);
            }

            this.each(getCustomPlugin);

            var args    = (arguments.length > 1) ? Array.prototype.slice.call(arguments, 1) : undefined;
            var results = [];

            function applyMethod(index) {
                var customPlugin = customPlugins[index];

                if (!customPlugin) {
                    console.warn('$.customPlugin not instantiated yet');
                    console.info(this);
                    results.push(undefined);
                    return;
                }

                if (typeof customPlugin[method] === 'function') {
                    var result = customPlugin[method].apply(customPlugin, args);
                    results.push(result);
                } else {
                    console.warn('Method \'' + method + '\' not defined in $.customPlugin');
                }
            }

            this.each(applyMethod);

            return (results.length > 1) ? results : results[0];
        } else {
            var options = (typeof methodOrOptions === 'object') ? methodOrOptions : undefined;

            function init() {
                var $el          = $(this);
                var customPlugin = new CustomPlugin($el, options);

                $el.data('customPlugin', customPlugin);
            }

            return this.each(init);
        }

    };

})(jQuery);

E a violino de trabalho.

Você notará como no primeiro violino, todos os divs sempre são movidos para a direita, exatamente o mesmo número de pixels. Isso é porque apenas 1 O objeto de opções existe para todos os elementos do seletor.

Usando a técnica escrita acima, você notará que, no segundo violino, cada div não está alinhado e é movido aleatoriamente (excluindo a primeira div, pois seu randomizador está sempre definido como 1 na linha 89). Isso ocorre porque agora estamos instanciando adequadamente uma nova instância de plug -in personalizada para cada elemento do seletor. Cada elemento tem seu próprio objeto de opções e não é salvo no seletor, mas na instância do próprio plug -in personalizado.

Isso significa que você poderá acessar os métodos do plug -in personalizado instanciados em um elemento específico no DOM dos novos seletores de jQuery e não são forçados a armazená -los em cache, como você estaria no primeiro violino.

Por exemplo, isso retornaria uma matriz de todos os objetos de opções usando a técnica no segundo violino. Retornaria indefinido no primeiro.

$('div').customPlugin();
$('div').customPlugin('options'); // would return an array of all options objects

É assim que você teria que acessar o objeto de opções no primeiro violino e retornaria apenas um único objeto, não uma matriz delas:

var divs = $('div').customPlugin();
divs.customPlugin('options'); // would return a single options object

$('div').customPlugin('options');
// would return undefined, since it's not a cached selector

Eu sugiro usar a técnica acima, não a da resposta atualmente selecionada.

JQuery tornou isso muito mais fácil com a introdução do Fábrica de widgets.

Exemplo:

$.widget( "myNamespace.myPlugin", {

    options: {
        // Default options
    },

    _create: function() {
        // Initialization logic here
    },

    // Create a public method.
    myPublicMethod: function( argument ) {
        // ...
    },

    // Create a private method.
    _myPrivateMethod: function( argument ) {
        // ...
    }

});

Inicialização:

$('#my-element').myPlugin();
$('#my-element').myPlugin( {defaultValue:10} );

Chamada de método:

$('#my-element').myPlugin('myPublicMethod', 20);

(É assim que o JQuery UI a biblioteca é construída.)

Uma abordagem mais simples é usar funções aninhadas. Então você pode acorrentá-los de maneira orientada a objetos. Exemplo:

jQuery.fn.MyPlugin = function()
{
  var _this = this;
  var a = 1;

  jQuery.fn.MyPlugin.DoSomething = function()
  {
    var b = a;
    var c = 2;

    jQuery.fn.MyPlugin.DoSomething.DoEvenMore = function()
    {
      var d = a;
      var e = c;
      var f = 3;
      return _this;
    };

    return _this;
  };

  return this;
};

E aqui está como chamá -lo:

var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();

Tenha cuidado. Você não pode chamar uma função aninhada até que ela tenha sido criada. Então você não pode fazer isso:

var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
pluginContainer.MyPlugin.DoSomething();

A função Doevenmore nem sequer existe porque a função doSomething ainda não foi executada, necessária para criar a função Doevenmore. Para a maioria dos plugins jQuery, você realmente terá apenas um nível de funções aninhadas e não duas, como mostrei aqui.
Apenas certifique -se de que, ao criar funções aninhadas, definir essas funções no início da função dos pais antes que qualquer outro código na função pai seja executado.

Por fim, observe que o membro "Este" é armazenado em uma variável chamada "_This". Para funções aninhadas, você deve retornar "_This" se precisar de uma referência à instância no cliente de chamada. Você não pode simplesmente retornar "isso" na função aninhada, porque isso retornará uma referência à função e não à instância do jQuery. O retorno de uma referência de jQuery permite que você acorrente os métodos de jQuery intrínsecos no retorno.

Eu entendi de JQuery Plugin Boilerplate

Também descrito em JQuery Plugin Boilerplate, Reprise

// jQuery Plugin Boilerplate
// A boilerplate for jumpstarting jQuery plugins development
// version 1.1, May 14th, 2011
// by Stefan Gabos

// remember to change every instance of "pluginName" to the name of your plugin!
(function($) {

    // here we go!
    $.pluginName = function(element, options) {

    // plugin's default options
    // this is private property and is accessible only from inside the plugin
    var defaults = {

        foo: 'bar',

        // if your plugin is event-driven, you may provide callback capabilities
        // for its events. execute these functions before or after events of your
        // plugin, so that users may customize those particular events without
        // changing the plugin's code
        onFoo: function() {}

    }

    // to avoid confusions, use "plugin" to reference the
    // current instance of the object
    var plugin = this;

    // this will hold the merged default, and user-provided options
    // plugin's properties will be available through this object like:
    // plugin.settings.propertyName from inside the plugin or
    // element.data('pluginName').settings.propertyName from outside the plugin,
    // where "element" is the element the plugin is attached to;
    plugin.settings = {}

    var $element = $(element), // reference to the jQuery version of DOM element
    element = element; // reference to the actual DOM element

    // the "constructor" method that gets called when the object is created
    plugin.init = function() {

    // the plugin's final properties are the merged default and
    // user-provided options (if any)
    plugin.settings = $.extend({}, defaults, options);

    // code goes here

   }

   // public methods
   // these methods can be called like:
   // plugin.methodName(arg1, arg2, ... argn) from inside the plugin or
   // element.data('pluginName').publicMethod(arg1, arg2, ... argn) from outside
   // the plugin, where "element" is the element the plugin is attached to;

   // a public method. for demonstration purposes only - remove it!
   plugin.foo_public_method = function() {

   // code goes here

    }

     // private methods
     // these methods can be called only from inside the plugin like:
     // methodName(arg1, arg2, ... argn)

     // a private method. for demonstration purposes only - remove it!
     var foo_private_method = function() {

        // code goes here

     }

     // fire up the plugin!
     // call the "constructor" method
     plugin.init();

     }

     // add the plugin to the jQuery.fn object
     $.fn.pluginName = function(options) {

        // iterate through the DOM elements we are attaching the plugin to
        return this.each(function() {

          // if plugin has not already been attached to the element
          if (undefined == $(this).data('pluginName')) {

              // create a new instance of the plugin
              // pass the DOM element and the user-provided options as arguments
              var plugin = new $.pluginName(this, options);

              // in the jQuery version of the element
              // store a reference to the plugin object
              // you can later access the plugin and its methods and properties like
              // element.data('pluginName').publicMethod(arg1, arg2, ... argn) or
              // element.data('pluginName').settings.propertyName
              $(this).data('pluginName', plugin);

           }

        });

    }

})(jQuery);

Tarde demais, mas talvez possa ajudar alguém um dia.

Eu estava na mesma situação, criando um plugin jQuery com alguns métodos e, depois de ler alguns artigos e alguns pneus, crio um plugin jQuery Boilerplate (https://github.com/acanimal/jquery-plugin-boilerplate).

Além disso, eu desenvolvo com ele um plug -in para gerenciar tags (https://github.com/acanimal/tagger.js) e escreveu duas postagens de blog explicando passo a passo a criação de um plugin jQuery (http://acurenimal.com/blog/2013/01/15/things-i-learned-creating-a-jquery-plugin-part-i/).

Você pode fazer:

(function ($) {

var YourPlugin = function (element, option) {
    var defaults = {
        //default value
    }

    this.option = $.extend({}, defaults, option);
    this.$element = $(element);
    this.init();
}

YourPlugin.prototype = {
    init: function () {
    },
    show: function() {

    },
    //another functions
}

$.fn.yourPlugin = function (option) {
    var arg = arguments,
        options = typeof option == 'object' && option;;
    return this.each(function () {
        var $this = $(this),
            data = $this.data('yourPlugin');

        if (!data) $this.data('yourPlugin', (data = new YourPlugin(this, options)));
        if (typeof option === 'string') {
            if (arg.length > 1) {
                data[option].apply(data, Array.prototype.slice.call(arg, 1));
            } else {
                data[option]();
            }
        }
    });
}; 
  });

Dessa forma, seu objeto de plugins é armazenado como valor de dados em seu elemento.

 //Initialization without option
 $('#myId').yourPlugin();

 //Initialization with option
 $('#myId').yourPlugin({
        //your option
 });

//call show method
$('#myId').yourPlugin('show');

Que tal usar gatilhos?Alguém conhece alguma desvantagem em usá-los?A vantagem é que todas as variáveis ​​internas são acessíveis através dos gatilhos e o código é muito simples.

Veja em jsfiddle.

Exemplo de uso

<div id="mydiv">This is the message container...</div>

<script>
    var mp = $("#mydiv").messagePlugin();

    // the plugin returns the element it is called on
    mp.trigger("messagePlugin.saySomething", "hello");

    // so defining the mp variable is not needed...
    $("#mydiv").trigger("messagePlugin.repeatLastMessage");
</script>

Plugar

jQuery.fn.messagePlugin = function() {

    return this.each(function() {

        var lastmessage,
            $this = $(this);

        $this.on('messagePlugin.saySomething', function(e, message) {
            lastmessage = message;
            saySomething(message);
        });

        $this.on('messagePlugin.repeatLastMessage', function(e) {
            repeatLastMessage();
        });

        function saySomething(message) {
            $this.html("<p>" + message + "</p>");
        }

        function repeatLastMessage() {
            $this.append('<p>Last message was: ' + lastmessage + '</p>');
        }

    });

}

Aqui, quero sugerir etapas para criar plug -in simples com argumentos.

JS

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

        // Default params
        var params = $.extend({
            text     : 'Default Title',
            fontsize : 10,
        }, options);
        return $(this).text(params.text);

    }
}(jQuery));

Aqui, adicionamos objeto padrão chamado params e defina valores padrão das opções usando extend função. Portanto, se aprovarmos o argumento em branco, ele definirá valores padrão em vez de definirá.

Html

$('.cls-title').myFirstPlugin({ text : 'Argument Title' });

Consulte Mais informação: Como criar plugin jQuery

Tente este:

$.fn.extend({
"calendar":function(){
    console.log(this);
    var methods = {
            "add":function(){console.log("add"); return this;},
            "init":function(){console.log("init"); return this;},
            "sample":function(){console.log("sample"); return this;}
    };

    methods.init(); // you can call any method inside
    return methods;
}}); 
$.fn.calendar() // caller or 
$.fn.calendar().sample().add().sample() ......; // call methods

Aqui está minha versão nua disso. Semelhante aos postados antes, você chamaria como:

$('#myDiv').MessagePlugin({ yourSettings: 'here' })
           .MessagePlugin('saySomething','Hello World!');

-ou acesse a instância diretamente @ plugin_MessagePlugin

$elem = $('#myDiv').MessagePlugin();
var instance = $elem.data('plugin_MessagePlugin');
instance.saySomething('Hello World!');

Messageplugin.js

;(function($){

    function MessagePlugin(element,settings){ // The Plugin
        this.$elem = element;
        this._settings = settings;
        this.settings = $.extend(this._default,settings);
    }

    MessagePlugin.prototype = { // The Plugin prototype
        _default: {
            message: 'Generic message'
        },
        initialize: function(){},
        saySomething: function(message){
            message = message || this._default.message;
            return this.$elem.html(message);
        }
    };

    $.fn.MessagePlugin = function(settings){ // The Plugin call

        var instance = this.data('plugin_MessagePlugin'); // Get instance

        if(instance===undefined){ // Do instantiate if undefined
            settings = settings || {};
            this.data('plugin_MessagePlugin',new MessagePlugin(this,settings));
            return this;
        }

        if($.isFunction(MessagePlugin.prototype[settings])){ // Call method if argument is name of method
            var args = Array.prototype.slice.call(arguments); // Get the arguments as Array
            args.shift(); // Remove first argument (name of method)
            return MessagePlugin.prototype[settings].apply(instance, args); // Call the method
        }

        // Do error handling

        return this;
    }

})(jQuery);

Isso pode realmente ser feito para funcionar de uma maneira "agradável" usando defineProperty. Onde "bom" significa sem ter que usar () Para obter o espaço para nome do plug -in nem ter que passar o nome da função por string.

Compatibilidade NIT: defineProperty Não funciona em navegadores antigos como o IE8 e abaixo.Embargo: $.fn.color.blue.apply(foo, args) Não vai funcionar, você precisa usar foo.color.blue.apply(foo, args).

function $_color(color)
{
    return this.css('color', color);
}

function $_color_blue()
{
    return this.css('color', 'blue');
}

Object.defineProperty($.fn, 'color',
{
    enumerable: true,
    get: function()
    {
        var self = this;

        var ret = function() { return $_color.apply(self, arguments); }
        ret.blue = function() { return $_color_blue.apply(self, arguments); }

        return ret;
    }
});

$('#foo').color('#f00');
$('#bar').color.blue();

Link jsfiddle

De acordo com o JQuery Standard, você pode criar plug -in da seguinte maneira:

(function($) {

    //methods starts here....
    var methods = {
        init : function(method,options) {
             this.loadKeywords.settings = $.extend({}, this.loadKeywords.defaults, options);
             methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
             $loadkeywordbase=$(this);
        },
        show : function() {
            //your code here.................
        },
        getData : function() {
           //your code here.................
        }

    } // do not put semi colon here otherwise it will not work in ie7
    //end of methods

    //main plugin function starts here...
    $.fn.loadKeywords = function(options,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 ' + method + ' does not ecw-Keywords');
        }
    };
    $.fn.loadKeywords.defaults = {
            keyName:     'Messages',
            Options:     '1',
            callback: '',
    };
    $.fn.loadKeywords.settings = {};
    //end of plugin keyword function.

})(jQuery);

Como chamar este plugin?

1.$('your element').loadKeywords('show',{'callback':callbackdata,'keyName':'myKey'}); // show() will be called

Referência: link

Eu acho que isso pode te ajudar ...

(function ( $ ) {
  
    $.fn.highlight = function( options ) {
  
        // This is the easiest way to have default options.
        var settings = $.extend({
            // These are the defaults.
            color: "#000",
            backgroundColor: "yellow"
        }, options );
  
        // Highlight the collection based on the settings variable.
        return this.css({
            color: settings.color,
            backgroundColor: settings.backgroundColor
        });
  
    };
  
}( jQuery ));

No exemplo acima, eu criei um jQuery simples realçar plugin.Eu compartilhei um artigo no qual eu havia discutido sobre Como criar seu próprio plugin jQuery do básico ao avanço. Eu acho que você deveria dar uma olhada ... http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/

A seguir, um pequeno plug-in para ter um método de aviso para fins de depuração. Mantenha este código no arquivo jquery.debug.js: js:

jQuery.fn.warning = function() {
   return this.each(function() {
      alert('Tag Name:"' + $(this).prop("tagName") + '".');
   });
};

Html:

<html>
   <head>
      <title>The jQuery Example</title>

      <script type = "text/javascript" 
         src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

      <script src = "jquery.debug.js" type = "text/javascript"></script>

      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("div").warning();
            $("p").warning();
         });
      </script> 
   </head>

   <body>
      <p>This is paragraph</p>
      <div>This is division</div>
   </body>

</html>

Aqui está como eu faço:

(function ( $ ) {

$.fn.gridview = function( options ) {

    ..........
    ..........


    var factory = new htmlFactory();
    factory.header(...);

    ........

};

}( jQuery ));


var htmlFactory = function(){

    //header
     this.header = function(object){
       console.log(object);
  }
 }

A seguinte estrutura de plug-in utiliza o jQuery-data()-método Para fornecer uma interface pública aos métodos/conjuntos de plug-in internos (enquanto preservam a cadeia jQuery):

(function($, window, undefined) {

  $.fn.myPlugin = function(options) {

    // settings, e.g.:  
    var settings = $.extend({
      elementId: null,
      shape: "square",
      color: "aqua",
      borderWidth: "10px",
      borderColor: "DarkGray"
    }, options);

    // private methods, e.g.:
    var setBorder = function(color, width) {        
      settings.borderColor = color;
      settings.borderWidth = width;          
      drawShape();
    };

    var drawShape = function() {         
      $('#' + settings.elementId).attr('class', settings.shape + " " + "center"); 
      $('#' + settings.elementId).css({
        'background-color': settings.color,
        'border': settings.borderWidth + ' solid ' + settings.borderColor      
      });
      $('#' + settings.elementId).html(settings.color + " " + settings.shape);            
    };

    return this.each(function() { // jQuery chainability     
      // set stuff on ini, e.g.:
      settings.elementId = $(this).attr('id'); 
      drawShape();

      // PUBLIC INTERFACE 
      // gives us stuff like: 
      //
      //    $("#...").data('myPlugin').myPublicPluginMethod();
      //
      var myPlugin = {
        element: $(this),
        // access private plugin methods, e.g.: 
        setBorder: function(color, width) {        
          setBorder(color, width);
          return this.element; // To ensure jQuery chainability 
        },
        // access plugin settings, e.g.: 
        color: function() {
          return settings.color;
        },        
        // access setting "shape" 
        shape: function() {
          return settings.shape;
        },     
        // inspect settings 
        inspectSettings: function() {
          msg = "inspecting settings for element '" + settings.elementId + "':";   
          msg += "\n--- shape: '" + settings.shape + "'";
          msg += "\n--- color: '" + settings.color + "'";
          msg += "\n--- border: '" + settings.borderWidth + ' solid ' + settings.borderColor + "'";
          return msg;
        },               
        // do stuff on element, e.g.:  
        change: function(shape, color) {        
          settings.shape = shape;
          settings.color = color;
          drawShape();   
          return this.element; // To ensure jQuery chainability 
        }
      };
      $(this).data("myPlugin", myPlugin);
    }); // return this.each 
  }; // myPlugin
}(jQuery));

Agora você pode chamar Methods de plug-in interno para acessar ou modificar dados do plug-in ou o elemento relevante usando esta sintaxe:

$("#...").data('myPlugin').myPublicPluginMethod(); 

Contanto que você devolva o elemento atual (this) de dentro da sua implementação de myPublicPluginMethod() Chainabilidade jQuery será preservada - portanto, os seguintes trabalhos:

$("#...").data('myPlugin').myPublicPluginMethod().css("color", "red").html("...."); 

Aqui estão alguns exemplos (para obter detalhes, checkout isto violino):

// initialize plugin on elements, e.g.:
$("#shape1").myPlugin({shape: 'square', color: 'blue', borderColor: 'SteelBlue'});
$("#shape2").myPlugin({shape: 'rectangle', color: 'red', borderColor: '#ff4d4d'});
$("#shape3").myPlugin({shape: 'circle', color: 'green', borderColor: 'LimeGreen'});

// calling plugin methods to read element specific plugin settings:
console.log($("#shape1").data('myPlugin').inspectSettings());    
console.log($("#shape2").data('myPlugin').inspectSettings());    
console.log($("#shape3").data('myPlugin').inspectSettings());      

// calling plugin methods to modify elements, e.g.:
// (OMG! And they are chainable too!) 
$("#shape1").data('myPlugin').change("circle", "green").fadeOut(2000).fadeIn(2000);      
$("#shape1").data('myPlugin').setBorder('LimeGreen', '30px');

$("#shape2").data('myPlugin').change("rectangle", "red"); 
$("#shape2").data('myPlugin').setBorder('#ff4d4d', '40px').css({
  'width': '350px',
  'font-size': '2em' 
}).slideUp(2000).slideDown(2000);              

$("#shape3").data('myPlugin').change("square", "blue").fadeOut(2000).fadeIn(2000);   
$("#shape3").data('myPlugin').setBorder('SteelBlue', '30px');

// etc. ...     

O que você fez é basicamente se estender JQuery.fn.MessagePlugin Objeto por novo método. O que é útil, mas não no seu caso.

Você tem que fazer é usar esta técnica

function methodA(args){ this // refers to object... }
function saySomething(message){ this.html(message);  to first function }

jQuery.fn.messagePlugin = function(opts) {
  if(opts=='methodA') methodA.call(this);
  if(opts=='saySomething') saySomething.call(this, arguments[0]); // arguments is an array of passed parameters
  return this.each(function(){
    alert(this);
  });

};

Mas você pode realizar o que você quer. Meu amigo ele começou a escrever sobre Lugins e como estendê -los com sua cadeia de funcionalidades aqui está o link para Seu blog

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top