문제

호출하는 개체에 추가 기능/메서드를 제공하는 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 플러그인 작성 페이지에 따르면 (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

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

선택된 객체는 MessagePlugin 클로저에 저장되며 해당 함수는 플러그인과 관련된 함수를 포함하는 객체를 리턴합니다. 각 함수에서 원하는 동작을 현재 선택한 객체에 수행 할 수 있습니다.

코드를 테스트하고 플레이 할 수 있습니다 여기.

편집하다: 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가 정렬되지 않고 무작위로 이동된다는 것을 알 수 있습니다(첫 번째 div는 제외하고, 첫 번째 div의 무작위 추출기는 89행에서 항상 1로 설정되어 있습니다).이는 이제 선택기의 모든 요소에 대해 새로운 사용자 정의 플러그인 인스턴스를 올바르게 인스턴스화하고 있기 때문입니다.모든 요소에는 고유한 옵션 개체가 있으며 선택기에 저장되지 않고 사용자 정의 플러그인 자체의 인스턴스에 저장됩니다.

즉, 새로운 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는 위젯 공장.

예시:

$.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 기능도 존재하지 않습니다. 대부분의 jQuery 플러그인의 경우, 여기에 표시된 것처럼 하나의 중첩 기능 만 가지게됩니다.
부모 함수의 다른 코드가 실행되기 전에 부모 함수의 시작 부분에서 이러한 함수를 정의하는 중첩 함수를 만들 때 확인하십시오.

마지막으로, "이"멤버는 "_this"라는 변수에 저장됩니다. 중첩 된 기능의 경우 호출 클라이언트의 인스턴스에 대한 참조가 필요한 경우 "_this"를 반환해야합니다. 중첩 된 함수에서 "this"를 반환 할 수는 없습니다. jQuery 인스턴스가 아닌 함수에 대한 참조를 반환하기 때문입니다. jQuery Reference를 반환하면 귀환시 고유의 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 플러그인을 만들 때 단계별로 설명하는 두 개의 블로그 게시물을 썼습니다 (http://acuriousanimal.com/blog/2013/01/15/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');

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

참조하십시오 jsfiddle.

예제 사용

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

    });

}

여기서는 인수가있는 간단한 플러그인을 만들기위한 단계를 제안하고 싶습니다.

JS

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

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

    }
}(jQuery));

여기에서 우리는 기본 객체를 추가했습니다 params 옵션의 기본값 값을 설정합니다 extend 기능. 따라서 공백 인수를 전달하면 대신 기본값이 설정됩니다. 그렇지 않으면 설정됩니다.

HTML

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

더 읽기 : 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!');

-또는 인스턴스에 직접 액세스 @ 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);

이것은 실제로 "좋은"방식으로 작동하도록 만들 수 있습니다. defineProperty. "좋은"곳은 사용하지 않고 의미합니다 () 플러그인 네임 스페이스를 가져 오거나 문자열별로 기능 이름을 전달해야합니다.

호환성 NIT : defineProperty IE8 이하와 같은 고대 브라우저에서는 작동하지 않습니다.경고: $.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 Standard에 따르면 플러그인을 다음과 같이 만들 수 있습니다.

(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를 만들었습니다. 가장 밝은 부분 플러그인. 나는 내가 논의한 기사를 공유했다. 자신의 jQuery 플러그인을 만드는 방법 기본에서 사전으로. 나는 당신이 그것을 확인해야한다고 생각합니다 ... 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-data()-방법 내부 플러그인-메드/-세팅에 대한 공개 인터페이스를 제공하기 위해 (jQuery-chainability를 보존하는 동안) :

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

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

$("#...").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. ...     

당신이 한 일은 기본적으로 확장됩니다 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 (). 내 친구 그는 루긴스에 대해 글을 쓰기 시작했고 여기에서 당신의 기능을 연장하는 방법은 다음과 같은 링크입니다. 그의 블로그

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top