programing

메소드를 사용하여 jQuery 플러그인을 만드는 방법은 무엇입니까?

muds 2023. 8. 14. 23:10
반응형

메소드를 사용하여 jQuery 플러그인을 만드는 방법은 무엇입니까?

호출하는 객체에 추가 기능/메소드를 제공하는 jQuery 플러그인을 작성하려고 합니다.제가 온라인에서 읽은 모든 튜토리얼(지난 2시간 동안 검색)에는 옵션을 추가하는 방법만 포함되어 있지만 추가 기능은 포함되어 있지 않습니다.

제가 원하는 것은 다음과 같습니다.

//div의 플러그인을 호출하여 div를 메시지 컨테이너로 포맷합니다.

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

아니면 그 노선들을 따라 무언가.요약하면 다음과 같습니다. 플러그인을 호출한 다음 플러그인과 관련된 함수를 호출합니다.이 작업을 수행할 방법을 찾을 수 없을 것 같고, 이전에 많은 플러그인이 이 작업을 수행하는 것을 보았습니다.

플러그인에 대해 지금까지 알고 있는 내용은 다음과 같습니다.

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

어떻게 하면 그런 것을 이룰 수 있을까요?

감사해요!


2013년 11월 18일 업데이트: 저는 하리의 다음 댓글과 업보의 정답을 변경했습니다.

jQuery Plugin Authoring 페이지(http://docs.jquery.com/Plugins/Authoring), 에 따르면 jQuery와 jQuery.fn 네임스페이스를 더럽히지 않는 것이 가장 좋습니다.그들은 다음 방법을 제안합니다.

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

기본적으로 함수를 배열(래핑 함수로 범위 지정)에 저장하고 전달된 매개 변수가 문자열인지 여부를 확인하고 매개 변수가 개체(또는 null)인 경우 기본 메서드("init" 여기서)로 되돌립니다.

그런 다음 방법을 그렇게 부를 수 있습니다.

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

Javascript "arguments" 변수는 전달된 모든 인수의 배열이므로 임의 길이의 함수 매개 변수로 작동합니다.

다음은 추가 방법으로 플러그인을 만드는 데 사용한 패턴입니다.다음과 같이 사용할 수 있습니다.

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

또는 메소드를 직접 호출하려면,

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

예:

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

이 접근 방식은 어떻습니까?

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

선택한 개체는 플러그인 폐쇄 메시지에 저장되며, 이 함수는 플러그인과 관련된 함수가 포함된 개체를 반환합니다. 이 함수에서는 현재 선택한 개체에 대해 원하는 작업을 수행할 수 있습니다.

당신은 여기서 코드를 테스트하고 놀 수 있습니다.

편집: jQuery 체인 기능을 유지하기 위해 코드가 업데이트되었습니다.

현재 선택한 답변의 문제는 선택기의 모든 요소에 대해 실제로 사용자 지정 플러그인의 새 인스턴스를 만들지 않는다는 것입니다.실제로는 단일 인스턴스만 생성하고 선택기 자체를 스코프로 전달합니다.

자세한 설명을 보려면 이 바이올린을 보십시오.

대신 jQuery.each를 사용하여 선택기를 루프하고 선택기의 모든 요소에 대해 사용자 지정 플러그인의 새 인스턴스를 인스턴스화해야 합니다.

방법:

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

그리고 일하는 바이올린.

첫 번째 피들에서 모든 div가 항상 정확히 같은 수의 픽셀로 오른쪽으로 이동되는 방식을 알게 될 것입니다.선택기의 모든 요소에 대해 하나의 옵션 개체만 존재하기 때문입니다.

위에 기술된 기법을 사용하면, 두 번째 바이올린에서 각 div가 정렬되지 않고 무작위로 이동한다는 것을 알 수 있습니다(랜덤라이저는 89행에서 항상 1로 설정되므로 첫 번째 div는 제외).이는 Selector의 모든 요소에 대해 새 사용자 지정 플러그인 인스턴스를 올바르게 인스턴스화하고 있기 때문입니다.모든 요소에는 고유한 옵션 개체가 있으며 선택기에 저장되지 않고 사용자 지정 플러그인 자체의 인스턴스에 저장됩니다.

즉, 새 jQuery 선택기에서 DOM의 특정 요소에 인스턴스화된 사용자 지정 플러그인의 메서드에 액세스할 수 있으며 첫 번째 중간에 있는 것처럼 강제로 캐시하지 않아도 됩니다.

예를 들어, 이것은 두 번째 피들의 매개 변수를 사용하는 모든 옵션 객체의 배열을 반환합니다.첫 번째에서 정의되지 않은 상태로 반환됩니다.

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

이렇게 하면 첫 번째 피들에서 옵션 개체에 액세스하고 개체 배열이 아닌 단일 개체만 반환할 수 있습니다.

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

현재 선택한 답변의 기술이 아닌 위의 기술을 사용하는 것이 좋습니다.

jQuery UI 위젯 팩토리를 사용합니다.

예:

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

초기화:

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

메서드 호출:

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

(jQuery UI 라이브러리는 이렇게 구성됩니다.)

더 간단한 방법은 중첩 함수를 사용하는 것입니다.그런 다음 객체 지향 방식으로 체인을 연결할 수 있습니다.예:

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

다음은 이를 설명하는 방법입니다.

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

그래도 조심하세요.중첩 함수를 만들 때까지 함수를 호출할 수 없습니다.따라서 이 작업을 수행할 수 없습니다.

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

DoEvenMore 기능은 DoEvenMore 기능을 만들기 위해 필요한 DoSomething 기능이 아직 실행되지 않았기 때문에 존재하지도 않습니다.대부분의 jQuery 플러그인의 경우 여기서 보여드린 것처럼 두 개가 아닌 한 개의 중첩 함수만 사용할 수 있습니다.
중첩 함수를 만들 때 상위 함수의 다른 코드가 실행되기 전에 상위 함수의 시작 부분에서 이러한 함수를 정의해야 합니다.

마지막으로, "이" 멤버는 "_this"라는 변수에 저장됩니다.중첩 함수의 경우 호출 클라이언트에서 인스턴스에 대한 참조가 필요한 경우 "_this"를 반환해야 합니다.jQuery 인스턴스가 아닌 함수에 대한 참조를 반환하기 때문에 중첩 함수에서 "이것"만 반환할 수는 없습니다.jQuery 참조를 반환하면 반환 시 고유 jQuery 메서드를 연결할 수 있습니다.

jQuery 플러그인 보일러 플레이트에서 받았습니다.

jQuery 플러그인 보일러 플레이트에도 설명되어 있으며, 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);

너무 늦었지만 언젠가 누군가에게 도움이 될 수도 있습니다.

저는 몇 가지 방법으로 jQuery 플러그인을 만들고, 몇 가지 기사와 타이어를 읽은 후 jQuery 플러그인 보일러 플레이트(https://github.com/acanimal/jQuery-Plugin-Boilerplate) 를 만드는 것과 같은 상황에 있었습니다.

또한 저는 태그를 관리하기 위한 플러그인(https://github.com/acanimal/tagger.js) 을 개발하고 jQuery 플러그인(https://www.acuriousanimal.com/blog/20130115/things-i-learned-creating-a-jquery-plugin-part-i) )의 생성을 단계별로 설명하는 두 개의 블로그 게시물을 작성했습니다.

할 수 있는 일:

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

이러한 방식으로 플러그인 개체는 요소에 데이터 값으로 저장됩니다.

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

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

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

트리거를 사용하는 것은 어떻습니까?그것들을 사용하는 것에 대한 단점을 아는 사람이 있습니까?이점은 트리거를 통해 모든 내부 변수에 액세스할 수 있으며 코드가 매우 간단하다는 것입니다.

jfiddle을 참조하십시오.

사용 예

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

플러그인

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

    });

}

여기서는 인수가 있는 간단한 플러그인을 만드는 단계를 제안하고자 합니다.

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

기본 개체인 에▁called▁default▁object다▁here를 추가했습니다.params합니다.extend기능. 됩니다. 않으면 따라서 빈 인수를 전달하면 기본값이 대신 설정됩니다. 그렇지 않으면 설정됩니다.

자세히 보기: JQuery 플러그인 생성 방법

사용해 보십시오.

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

이것은 제가 맨뼈로 만든 버전입니다.이전에 게시된 내용과 유사하게 다음과 같은 전화를 걸 수 있습니다.

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

@ -instance에 액세스합니다. @plugin_MessagePlugin

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

메시지 플러그인.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);

다음 플러그인 구조는 jQuery--methoddata() 사용하여 내부 플러그인-method/-설정에 대한 공용 인터페이스를 제공합니다(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));

이제 다음 구문을 사용하여 내부 플러그인 메서드를 호출하여 플러그인 데이터 또는 관련 요소에 액세스하거나 수정할 수 있습니다.

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

구현 내부에서 현재 요소(이 요소)를 반환하는 한myPublicPluginMethod()jQuery-chainability는 유지되므로 다음 작업이 수행됩니다.

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

다음은 몇 가지 예입니다(자세한 내용은 이 바이올린 체크아웃).

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

이것은 실제로 다음을 사용하여 "좋은" 방식으로 작동할 수 있습니다.defineProperty여기서 "좋다"는 의미는 사용할 필요가 없습니다.()플러그인 네임스페이스를 가져오거나 함수 이름을 문자열로 전달할 필요가 없습니다.

호환성 nit: definePropertyIE8 이하의 고대 브라우저에서는 작동하지 않습니다.주의사항: $.fn.color.blue.apply(foo, args)작동하지 않습니다. 사용해야 합니다.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 링크

jquery 표준에 따라 다음과 같이 플러그인을 생성할 수 있습니다.

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

이 플러그인을 어떻게 부르나요?

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

참조: 링크

이게 도움이 될 것 같아요

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

위의 예에서 나는 간단한 jquery 하이라이트 플러그인을 만들었습니다.저는 Basic에서 Advanced로 How to Create Your Own jQuery Plugin에 대해 논의한 기사를 공유했습니다.제 생각에 당신은 그것을 확인해야 할 것 같습니다...http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/

다음은 디버깅을 위해 경고 방법을 사용하는 작은 플러그인입니다.이 코드를 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>

방법은 다음과 같습니다.

(function ( $ ) {

$.fn.gridview = function( options ) {

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


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

    ........

};

}( jQuery ));


var htmlFactory = function(){

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

당신이 한 것은 기본적으로 jQuery.fn.messagePlugin 객체를 새로운 방법으로 확장하는 것입니다.그것은 유용하지만 당신의 경우에는 그렇지 않습니다.

당신은 이 기술을 사용해서 해야 합니다.

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

};

하지만 원하는 것을 달성할 수 있습니다. 즉, $("#mydiv").messagePlugin().saySomething("안녕하세요"); 제 친구는 루긴에 대해 쓰기 시작했고 여기서 당신의 기능 체인으로 그것들을 확장하는 방법을 그의 블로그 링크입니다.

언급URL : https://stackoverflow.com/questions/1117086/how-to-create-a-jquery-plugin-with-methods

반응형