Jak utworzyć wtyczkę jQuery z metodami?

Próbuję napisać wtyczkę jQuery, która dostarczy dodatkowe funkcje/metody obiektowi, który go wywołuje. Wszystkie tutoriale, które czytałem online (przeglądałem przez ostatnie 2 godziny), zawierają co najwyżej sposób dodawania opcji, ale nie dodatkowe funkcje.

Oto co chcę zrobić:

/ / sformatuj div aby był kontenerem wiadomości przez wywołanie wtyczki dla tego div

$("#mydiv").messagePlugin();
$("#mydiv").messagePlugin().saySomething("hello");
Albo coś w tym stylu. Oto do czego to się sprowadza: wzywam plugin, następnie nazywam funkcję związaną z tą wtyczką. Nie mogę znaleźć sposobu, aby to zrobić, i widziałem wiele wtyczek to zrobić wcześniej.

Oto co mam do tej pory na 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);
  }
};

Jak mogę osiągnąć coś takiego?

Dziękuję!

Aktualizacja 18 listopada 2013: zmieniłem poprawną odpowiedź na następujące komentarze i głosy Hari.

Author: Yuval Karmi, 2009-07-12

20 answers

Zgodnie ze stroną jQuery Plugin Authoring ( http://docs.jquery.com/Plugins/Authoring ), najlepiej nie mrugać jQuery i jQuery.przestrzenie nazw fn. Sugerują tę metodę:

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

Zasadniczo przechowujesz swoje funkcje w tablicy (z zakresem do funkcji owijania) i sprawdzasz, czy przekazywany parametr jest ciągiem znaków, powracając do metody domyślnej ("init" tutaj), jeśli parametr jest obiektem (lub null).

Wtedy można wywołać metody takie jak więc...

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

Zmienna Javascripts "arguments" jest tablicą wszystkich przekazywanych argumentów, więc działa z dowolnymi długościami parametrów funkcji.

 315
Author: Hari Honor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-02 16:19:44

Oto wzór, którego użyłem do tworzenia wtyczek z dodatkowymi metodami. Użyłbyś go tak:

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

Lub, aby wywołać metodę bezpośrednio,

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

Przykład:

;(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);
 56
Author: tvanfosson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-13 03:10:10

Co z tym podejściem:

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

Wybrane obiekty są przechowywane w zamknięciu messagePlugin, a ta funkcja zwraca obiekt, który zawiera funkcje związane z wtyczką, w każdej funkcji można wykonać żądane działania do aktualnie wybranych obiektów.

Możesz przetestować i pobawić się kodem tutaj .

Edit: zaktualizowany kod, aby zachować moc łańcucha jQuery.

 35
Author: Christian C. Salvadó,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-20 09:12:55

Problem z aktualnie wybraną odpowiedzią polega na tym, że nie tworzysz nowej instancji niestandardowej wtyczki dla każdego elementu w selektorze, tak jak myślisz, że robisz... w rzeczywistości tworzysz tylko jedną instancję i przekazujesz selektor jako zakres.

Zobacz to skrzypce dla głębszego wyjaśnienia.

Zamiast tego, musisz zapętlić selektor używając jQuery.każda i tworzy nową instancję niestandardowej wtyczki dla każdy element w selektorze.

Oto jak:

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

I pracujące skrzypce .

Zauważysz, że w pierwszych skrzypcach wszystkie div są zawsze przesuwane w prawo o dokładnie takiej samej liczbie pikseli. Dzieje się tak dlatego, że tylko jeden obiekt options istnieje dla wszystkich elementów w selektorze.

Używając techniki napisanej powyżej, zauważysz, że w drugim wierszu każdy div nie jest wyrównany i jest losowo przesuwany (wyłączając pierwszy div, ponieważ jest randomizerem jest zawsze ustawiona na 1 na linii 89). Dzieje się tak dlatego, że teraz prawidłowo tworzymy nową niestandardową instancję wtyczki dla każdego elementu w selektorze. Każdy element ma swój własny obiekt options i nie jest zapisywany w selektorze, ale w przypadku samej wtyczki niestandardowej.

Oznacza to, że będziesz mógł uzyskać dostęp do metod niestandardowych wtyczek utworzonych na określonym elemencie w DOM z nowych selektorów jQuery i nie będziesz zmuszony do ich buforowania, jak w pierwszym fiddle.

Na przykład, zwróci to tablicę wszystkich obiektów options wykorzystujących technikę w drugim wierszu. Powróci nieokreślony w pierwszym.

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

W ten sposób będziesz musiał uzyskać dostęp do obiektu options w pierwszym wierszu i zwrócić tylko jeden obiekt, a nie tablicę z nich:

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

Sugerowałbym użycie powyższej techniki, a nie tej z aktualnie wybranej odpowiedzi.

 18
Author: Kevin Jurkowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-09 19:10:02

JQuery ułatwiło to wprowadzenie Widget Factory .

Przykład:

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

});

Inicjalizacja:

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

Wywołanie metody:

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

(w ten sposób zbudowana jest biblioteka jQuery UI.)

 16
Author: Yarin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-28 18:08:50

Prostszym podejściem jest użycie funkcji zagnieżdżonych. Następnie możesz je łańcuchować w sposób zorientowany obiektowo. Przykład:

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

A oto jak to nazwać:

var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
Bądź ostrożny. Funkcja zagnieżdżona nie może zostać wywołana dopóki nie zostanie utworzona. Więc nie możesz tego zrobić:
var pluginContainer = $("#divSomeContainer");
pluginContainer.MyPlugin();
pluginContainer.MyPlugin.DoSomething.DoEvenMore();
pluginContainer.MyPlugin.DoSomething();

Funkcja DoEvenMore nawet nie istnieje, ponieważ funkcja DoSomething nie została jeszcze uruchomiona, co jest wymagane do utworzenia funkcji DoEvenMore. Dla większości wtyczek jQuery, naprawdę jesteś tylko będzie miał JEDEN poziom zagnieżdżonych funkcji, a nie dwa, jak pokazałem tutaj.
Po prostu upewnij się, że podczas tworzenia funkcji zagnieżdżonych definiujesz te funkcje na początku ich funkcji nadrzędnej, zanim jakikolwiek inny kod w funkcji nadrzędnej zostanie wykonany.

Na koniec zauważ, że element " this "jest przechowywany w zmiennej o nazwie"_this". W przypadku funkcji zagnieżdżonych, powinieneś zwrócić "_this", jeśli potrzebujesz odwołania do instancji w kliencie wywołującym. Nie można po prostu zwrócić " tego" w zagnieżdżonej funkcji, ponieważ zwróci odwołanie do funkcji, a nie instancji jQuery. Zwracanie referencji jQuery pozwala na łączenie wewnętrznych metod jQuery po powrocie.

 13
Author: Polaris431,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-20 20:21:18

Dostałem go z jQuery Plugin Boilerplate

Opisany również w 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);
 9
Author: MaxEcho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-23 05:55:26

Za późno, ale może kiedyś komuś pomoże.

Byłem w takiej samej sytuacji, jak tworzenie wtyczki jQuery z niektórymi metodami, a po przeczytaniu kilku artykułów i kilku opon tworzę jQuery plugin boilerplate ( https://github.com/acanimal/jQuery-Plugin-Boilerplate).

DODATKOWO rozwijam z nim plugin do zarządzania tagami ( https://github.com/acanimal/tagger.js) i napisał dwa posty na blogu wyjaśniające krok po kroku tworzenie wtyczki jQuery (http://acuriousanimal.com/blog/2013/01/15/things-i-learned-creating-a-jquery-plugin-part-i/).

 6
Author: EricSonaron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-10 18:06:40

Możesz zrobić:

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

W ten sposób Twój obiekt plugins jest przechowywany jako wartość danych w Twoim elemencie.

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

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

// call show method
$('#myId').yourPlugin('show');
 5
Author: Mazaher Bazari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-04 13:33:26

A co z użyciem wyzwalaczy? Czy ktoś zna jakieś wady ich używania? Zaletą jest to, że wszystkie wewnętrzne zmienne są dostępne za pośrednictwem wyzwalaczy, a kod jest bardzo prosty.

Patrz na jsfiddle .

Przykładowe użycie

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

Plugin

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

    });

}
 3
Author: István Ujj-Mészáros,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-27 00:48:39

Tutaj chcę zasugerować kroki, aby utworzyć prosty plugin z argumentami.

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

$('.cls-title').myFirstPlugin({ text : 'Argument Title' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 class="cls-title"></h1>

Tutaj dodaliśmy domyślny obiekt o nazwie params i ustawiliśmy domyślne wartości opcji za pomocą funkcji extend. Stąd, jeśli przekażemy pusty argument, to ustawi domyślne wartości zamiast tego, w przeciwnym razie będzie ustawiony.

Czytaj więcej: Jak utworzyć wtyczkę JQuery

 3
Author: Gopal Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-04 13:30:37

Spróbuj tego:

$.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
 2
Author: Serkan KONAKCI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-30 17:48:21

Oto moja wersja tego. Podobne do tych zamieszczonych wcześniej, możesz zadzwonić jak:

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

- lub dostęp do instancji bezpośrednio @ 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);
 1
Author: jtrumbull,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-02 01:00:56

Następująca struktura wtyczek wykorzystuje jQuery-data()-method , aby zapewnić publiczny interfejs do wewnętrznych metod wtyczek / ustawień (zachowując jQuery-chainability):

(function($, window, undefined) { 
  const defaults = {
    elementId   : null,
    shape       : "square",
    color       : "aqua",
    borderWidth : "10px",
    borderColor : "DarkGray"
  };

  $.fn.myPlugin = function(options) {
    // settings, e.g.:  
    var settings = $.extend({}, defaults, 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));

Teraz możesz wywołać wewnętrzne metody wtyczki, aby uzyskać dostęp lub zmodyfikować dane wtyczki lub odpowiedni element za pomocą tej składni:

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

Tak długo, jak zwracasz bieżący element (this) z wnętrza implementacji myPublicPluginMethod() jQuery-chainability zostaną zachowane - tak więc następujące dzieła:

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

Oto kilka przykładów (po szczegóły sprawdź to 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. ...     
 1
Author: Mayinx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-04 13:36:36

To może być rzeczywiście wykonane do pracy w "miły" sposób za pomocą defineProperty. Gdzie "nice" oznacza bez konieczności używania (), aby uzyskać Przestrzeń nazw wtyczki, ani konieczności przekazywania nazwy funkcji przez łańcuch znaków.

Kompatybilność nit: defineProperty nie działa w starożytnych przeglądarkach, takich jak IE8 i poniżej. Zastrzeżenie: $.fn.color.blue.apply(foo, args) nie zadziała, musisz użyć 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();

Jsfiddle link

 0
Author: kralyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-05 14:02:15

Zgodnie ze standardem jquery można utworzyć wtyczkę w następujący sposób:

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

Jak wywołać tę wtyczkę?

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

Reference: link

 0
Author: Mahesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-27 06:02:39

Myślę, że to może Ci pomóc...

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

W powyższym przykładzie stworzyłem prostą wtyczkę jquery highlight .Udostępniłem artykuł, w którym omówiłem o Jak stworzyć własną wtyczkę jQuery od Basic do Advance. Myślę, że powinieneś to sprawdzić... http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/

 0
Author: Shubham Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-07 22:00:53

Poniżej znajduje się mała wtyczka, aby mieć metodę ostrzegania dla celów debugowania. Zachowaj ten kod w jquery.debugowanie.plik 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>
 0
Author: jayaweb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-16 08:11:56

Oto Jak to robię:

(function ( $ ) {

$.fn.gridview = function( options ) {

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


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

    ........

};

}( jQuery ));


var htmlFactory = function(){

    //header
     this.header = function(object){
       console.log(object);
  }
 }
 0
Author: Mina Gabriel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-25 03:39:13

To co zrobiłeś to rozszerzenie jQuery.fn.obiekt messagePlugin przy pomocy nowej metody. Co jest przydatne, ale nie w Twoim przypadku.

Musisz to zrobić używając tej techniki

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

};

Ale możesz osiągnąć to, co chcesz mam na myśli, że jest sposób, aby zrobić $("#mydiv").messagePlugin ().say something ("hello"); mój przyjaciel zaczął pisać o lugins i jak je rozszerzyć z łańcucha funkcjonalności oto link do jego blog

 -2
Author: James,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-20 04:05:32