سؤال

أحاول كتابة مسافة جائق ستقدم وظائف / طرق إضافية للكائن الذي يطلق عليه. جميع البرامج التعليمية التي قرأتها عبر الإنترنت (تم التصفح لمدة الساعتين الماضية) تشمل، على الأكثر، كيفية إضافة خيارات، ولكن ليست وظائف إضافية.

إليك ما أتطلع إليه:

// تنسيق 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);
  }
};

كيف يمكنني تحقيق شيء من هذا القبيل؟

شكرا لك!


قم بتحديث 18 نوفمبر 2013: لقد غيرت الإجابة الصحيحة على تعليقات Hari التالية واختراقها.

هل كانت مفيدة؟

المحلول

وفقا لصفحة التأليف المساعد 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 );

في الأساس يمكنك تخزين الوظائف الخاصة بك في صفيف (استبدالها إلى وظيفة التغليف) وتحقق من إدخال إذا كانت المعلمة مرت هي سلسلة، والتحال إلى طريقة افتراضية ("INITE" هنا) إذا كانت المعلمة كائن (أو NULL).

ثم يمكنك استدعاء طرق مثل ...

$('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 "الوسائط" مجموعة من جميع الحجج التي تم تمريرها بحيث تعمل مع أطوال تعسفية لمعلمات الوظائف.

نصائح أخرى

إليك النمط الذي استخدمته لإنشاء الإضافات بطرق إضافية. سوف تستخدمها مثل:

$('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.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);

و عمل الكمان.

ستلاحظ كيف تعمل في أول كمان، يتم دائما نقل جميع Divs إلى اليمين نفس العدد بالضبط من البكسل. هذا بسبب فقط واحد كائن الخيارات موجود لجميع العناصر في المحدد.

باستخدام التقنية المكتوبة أعلاه، ستلاحظ أنه في الكمان الثاني، لا يتم محاذاة كل DIC ويتم نقلها بشكل عشوائي (باستثناء Div أولا كما يتم تعيين العوامل عشوائي دائما إلى 1 على السطر 89). هذا هو أننا الآن نحن الآن مثيل بشكل صحيح مثيل إضافي مخصص جديد لكل عنصر في المحدد. يحتوي كل عنصر على كائن خيارات خاص به ولا يتم حفظه في المحدد، ولكن في مثيل البرنامج المساعد المخصص نفسه.

هذا يعني أنك ستتمكن من الوصول إلى طرق Information المكون الإضافي لعنصر محدد في 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 حتى لأن وظيفة Dosomething لم يتم تشغيلها بعد والتي يجب أن تكون مطلوبة لإنشاء وظيفة DoevenMore. بالنسبة لمعظم الإضافات JQuery، فإنك ستحصل فقط على مستوى واحد من الوظائف المتداخلة وليس اثنين كما أظهرت هنا.
فقط تأكد من أنه عند إنشاء وظائف متداخلة تحدد هذه الوظائف في بداية دالة الوالدين قبل تنفيذ أي رمز آخر في الدالة الأصل.

أخيرا، لاحظ أن "هذا" يتم تخزين "هذا" في متغير يسمى "_THIS". بالنسبة للوظائف المتداخلة، يجب عليك إرجاع "_THIS" إذا كنت بحاجة إلى مرجع إلى المثيل في عميل الاتصال. لا يمكنك فقط إرجاع "هذا" في الوظيفة المتداخلة لأن ذلك سيعود مرجع إلى الوظيفة وليس مثيل JQuery. إرجاع مرجع مسج يسمح لك بسلسلة أساليب مسج جوهرية عند الإرجاع.

حصلت عليه من JQuery Plugin BeilerPlate.

كما هو موضح في 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);

بعد فوات الأوان ولكن ربما يمكن أن تساعد شخصا في يوم من الأيام.

كنت في نفس الوضع مثل، إنشاء مسافة مسج مع بعض الأساليب، وبعد قراءة بعض المقالات وبعض الإطارات، أقوم بإنشاء أداة مساعدة مسج مسج (https://github.com/acanimal/jquery-plugin-boilerplate.).

بالإضافة إلى ذلك، أتطور معها البرنامج المساعد لإدارة العلامات (https://github.com/acanimal/tagger.js.) وكتب مديرين بلوق يشرح خطوة بخطوة إنشاء مسافة مسج (http://acuriousanimal.com/blogoyx/201/01/15/Things-i-Learned-CreateDing-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>');
        }

    });

}

هنا أريد أن أقترح خطوات إنشاء مكون إضافي بسيط مع الوسائط.

ج إس

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

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

    }
}(jQuery));

هنا، أضفنا كائن افتراضي يسمى params وتعيين القيم الافتراضية للخيارات باستخدام extend وظيفة. وبالتالي، إذا نجحنا في حجة فارغة، فسيحدد القيم الافتراضية بدلا من ذلك، وسيتم تعيينها.

لغة البرمجة

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

اقرأ أكثر: كيفية إنشاء مسج البرنامج المساعد

جرب هذه:

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

وفقا لمعيار 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 ));

في المثال أعلاه كنت قد أنشأت مسج بسيط تسليط الضوء البرنامج المساعد "لقد شاركت مقالا ناقشته كيفية إنشاء البرنامج المساعد الخاص بجائق الخاص بك من الأساسي إلى التقدم. أعتقد أنك يجب عليك التحقق من ذلك ... 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>
   <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()-طريقة لتوفير واجهة عامة للمستقبلات المكونات الإضافية الداخلية / -Settings (مع الحفاظ على مستقر المستقر):

(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() سيتم الحفاظ على مستقر chainerability - لذلك الأعمال التالية:

$("#...").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 (). شيء سوى ("مرحبا")؛ صديقي بدأ يكتب عن Lugins وكيفية تمديدها مع سلسلة chainf الخاصة بك من وظائفك هنا هو الرابط مدونته

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top