with una tablas tabla plugin official enlace ejemplos datos create crear con agregar javascript jquery jquery-plugins javascript-framework

javascript - una - jquery official



¿Cómo crear un plugin jQuery con métodos? (20)

¿Qué pasa con el uso de desencadenadores? ¿Alguien sabe algún inconveniente al usarlos? El beneficio es que todas las variables internas son accesibles a través de los disparadores, y el código es muy simple.

Ver en jsfiddle .

Ejemplo 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>

Enchufar

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>''); } }); }

Intento escribir un plugin de jQuery que proporcione funciones / métodos adicionales al objeto que lo llama. Todos los tutoriales que leí en línea (he estado navegando durante las últimas 2 horas) incluyen, a lo sumo, cómo agregar opciones, pero no funciones adicionales.

Esto es lo que estoy buscando hacer:

// format div para ser un contenedor de mensajes al llamar al plugin para ese div

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

O algo por el estilo. Esto es lo que se reduce a: llamo al complemento, luego llamo a una función asociada con ese complemento. Parece que no puedo encontrar la manera de hacerlo, y he visto muchos complementos hacerlo antes.

Esto es lo que tengo hasta ahora para el complemento:

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); } };

¿Cómo puedo lograr algo así?

¡Gracias!

Actualizar el 18 de noviembre de 2013: Cambié la respuesta correcta a la de los siguientes comentarios y votaciones ascendentes de Hari.


¿Qué pasa con este enfoque?

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'');

Los objetos seleccionados se almacenan en el mensaje Cierre de archivo y esa función devuelve un objeto que contiene las funciones asociadas con el complemento, en cada función puede realizar las acciones deseadas para los objetos seleccionados actualmente.

Puedes probar y jugar con el código here .

Editar: Código actualizado para preservar el poder de la chainable jQuery.


Aquí está mi versión escueta de esto. Similar a los publicados anteriormente, llamarías como:

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

-o acceda directamente a la instancia @ 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);


Aquí quiero sugerir pasos para crear un plugin simple con argumentos.

JS

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

Aquí, hemos agregado el objeto predeterminado llamado params y establecemos los valores predeterminados de las opciones usando la función extend . Por lo tanto, si pasamos el argumento en blanco, establecerá los valores predeterminados, de lo contrario se establecerá.

HTML

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

Leer más: Cómo crear el plugin JQuery


Así es como lo hago:

(function ( $ ) { $.fn.gridview = function( options ) { .......... .......... var factory = new htmlFactory(); factory.header(...); ........ }; }( jQuery )); var htmlFactory = function(){ //header this.header = function(object){ console.log(object); } }


Creo que esto podría ayudarte ...

(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 ));

En el ejemplo anterior, había creado un complemento de jquery highlight simple. Había compartido un artículo en el que había discutido sobre Cómo crear tu propio jQuery Plugin desde Basic hasta Advance. Creo que deberías echarle un vistazo ... http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/


De acuerdo con el estándar jquery, puede crear el plugin de la siguiente manera:

(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);

¿Cómo llamar a este complemento?

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

Referencia: link


De acuerdo con la página de creación de jQuery Plugin ( http://docs.jquery.com/Plugins/Authoring ), es mejor no ensuciar los espacios de nombres jQuery y jQuery.fn. Sugieren 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 );

Básicamente, usted almacena sus funciones en una matriz (en función de la función de envoltura) y busca una entrada si el parámetro pasado es una cadena, volviendo a un método predeterminado ("init" aquí) si el parámetro es un objeto (o nulo).

Entonces puedes llamar a los métodos así ...

$(''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

La variable de Javascripts "arguments" es una matriz de todos los argumentos pasados, por lo que funciona con longitudes arbitrarias de parámetros de funciones.


Demasiado tarde, pero tal vez pueda ayudar a alguien algún día.

Estaba en la misma situación, creando un plugin de jQuery con algunos métodos, y después de leer algunos artículos y algunos neumáticos, creo un complemento de jQuery ( https://github.com/acanimal/jQuery-Plugin-Boilerplate ).

Además, desarrollo con un plugin para administrar etiquetas ( https://github.com/acanimal/tagger.js ) y escribí dos entradas de blog que explican paso a paso la creación de un plugin jQuery ( http://acuriousanimal.com/blog/2013/01/15/things-i-learned-creating-a-jquery-plugin-part-i/ ).


El problema con la respuesta seleccionada actualmente es que en realidad no está creando una nueva instancia del complemento personalizado para cada elemento del selector como cree que está haciendo ... en realidad solo está creando una sola instancia y transfiriendo el selector en sí como el alcance.

Ver este violín para una explicación más profunda.

En su lugar, deberá recorrer el selector mediante jQuery.each y crear una nueva instancia del complemento personalizado para cada elemento del selector.

Así es cómo:

(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);

Y un violín de trabajo .

Notarás cómo en el primer violín, todos los divs siempre se mueven hacia la derecha con el mismo número exacto de píxeles. Eso es porque solo existe un objeto de opciones para todos los elementos en el selector.

Usando la técnica escrita arriba, notarás que en el segundo violín, cada div no está alineado y se mueve al azar (excluyendo el primer div ya que su aleatorizador siempre se establece en 1 en la línea 89). Esto se debe a que ahora estamos instanciando correctamente una nueva instancia de complemento personalizado para cada elemento en el selector. Cada elemento tiene su propio objeto de opciones y no se guarda en el selector, sino en la instancia del plugin personalizado.

Esto significa que podrá acceder a los métodos del complemento personalizado instanciado en un elemento específico en el DOM desde los nuevos selectores jQuery y no está obligado a almacenarlos en la memoria caché, como lo haría en el primer violín.

Por ejemplo, esto devolvería una matriz de todos los objetos de opciones usando la técnica en el segundo violín. Volvería indefinido en el primero.

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

Así es como tendría que acceder al objeto de opciones en el primer violín y solo devolvería un solo objeto, no una matriz de ellos:

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

Sugeriría usar la técnica anterior, no la de la respuesta seleccionada actualmente.


Este es el patrón que he usado para crear complementos con métodos adicionales. Lo usarías como:

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

o, para invocar un método directamente,

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

Ejemplo:

;(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);


Esto realmente se puede hacer para que funcione de una manera "agradable" utilizando defineProperty . Donde "agradable" significa sin tener que usar () para obtener el espacio de nombre del complemento ni tener que pasar el nombre de la función por cadena.

Compatibilidad nit: defineProperty no funciona en navegadores antiguos como IE8 y abajo. Advertencia: $.fn.color.blue.apply(foo, args) no funcionará, debe 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();

Enlace JSFiddle


La siguiente estructura de plugins utiliza jQuery- data() -method para proporcionar una interfaz pública a plugin-methods / -settings internos (conservando jQuery-chainable):

(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));

Ahora puede llamar a los métodos internos de complementos para acceder o modificar los datos del plugin o el elemento relevante utilizando esta sintaxis:

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

Siempre que devuelva el elemento actual (esto) desde el interior de su implementación de myPublicPluginMethod() se conservará jQuery-chainability, por lo que lo siguiente funciona:

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

Aquí hay algunos ejemplos (para más detalles, consulte este fiddle ):

// 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. ...


Lo obtuve de jQuery Plugin Boilerplate

También se describe en 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);


Lo que sigue es un pequeño complemento para tener un método de advertencia para el propósito de la depuración. Guarde este código en el archivo 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>


Prueba 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


Tu puedes hacer:

(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](); } } }); }; });

De esta forma, su objeto de complementos se almacena como valor de datos en su elemento.

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


Un enfoque más simple es usar funciones anidadas. Luego puedes encadenarlos de forma orientada a objetos. Ejemplo:

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; };

Y así es como llamarlo:

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

Ten cuidado, sin embargo. No puede llamar a una función anidada hasta que se haya creado. Entonces no puedes hacer esto:

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

La función DoEvenMore ni siquiera existe porque todavía no se ha ejecutado la función DoSomething, que es necesaria para crear la función DoEvenMore. Para la mayoría de los complementos de jQuery, realmente solo tendrá un nivel de funciones anidadas y no dos como he mostrado aquí.
Solo asegúrese de que cuando cree funciones anidadas defina estas funciones al principio de su función primaria antes de que se ejecute cualquier otro código en la función principal.

Finalmente, tenga en cuenta que el miembro "this" está almacenado en una variable llamada "_this". Para las funciones anidadas, debe devolver "_this" si necesita una referencia a la instancia en el cliente que realiza la llamada. No puede simplemente devolver "this" en la función anidada porque devolverá una referencia a la función y no a la instancia de jQuery. Devolver una referencia de jQuery le permite encadenar métodos de jQuery intrínsecos a la vuelta.


jQuery lo ha simplificado mucho con la presentación de Widget Factory .

Ejemplo:

$.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 ) { // ... } });

Inicialización:

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

Método de llamada:

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

(Así es como se construye la biblioteca jQuery UI .)


What you did is basically extending jQuery.fn.messagePlugin object by new method. Which is useful but not in your case.

You have to do is using this technique

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); }); };

But you can accomplish what you want I mean there is a way to do $("#mydiv").messagePlugin().saySomething("hello"); My friend he started writing about lugins and how to extend them with your chainf of functionalities here is the link to his blog