2

私はまだプラグインの手順を理解しようとしているので、自分で書いたり、別のものを適応させたりできます。

このプラグインから学習しようとします fn.extend でメソッドを設定し、jquery.extend で作成された関数に (これで) 自分自身を渡します。

jQuery.fn.extend({
    everyTime: function(interval, label, fn, times) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times);
        });
    },

それを行わない他のプラグインも見ます。

何故ですか??またはその背後にあるアイデアは何ですか。

(1つは関数に使用され、もう1つはメソッドに使用されるという他の説明をいくつか読みましたが、それは私にとってあいまいです。)

ありがとう、リチャード

編集

2 つの異なる extends を使用する完全なプラグイン コード

jQuery.fn.extend({
    everyTime: function(interval, label, fn, times) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.extend({
    timer: {
        global: [],
        guid: 1,
        dataKey: "jQuery.timer",
        regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseFloat(result[1]);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times) {
            var counter = 0;

            if (jQuery.isFunction(label)) {
                if (!times) 
                    times = fn;
                fn = label;
                label = interval;
            }

            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval < 0)
                return;

            if (typeof times != 'number' || isNaN(times) || times < 0) 
                times = 0;

            times = times || 0;

            var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

            if (!timers[label])
                timers[label] = {};

            fn.timerID = fn.timerID || this.guid++;

            var handler = function() {
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
            };

            handler.timerID = fn.timerID;

            if (!timers[label][fn.timerID])
                timers[label][fn.timerID] = window.setInterval(handler,interval);

            this.global.push( element );

        },
        remove: function(element, label, fn) {
            var timers = jQuery.data(element, this.dataKey), ret;

            if ( timers ) {

                if (!label) {
                    for ( label in timers )
                        this.remove(element, label, fn);
                } else if ( timers[label] ) {
                    if ( fn ) {
                        if ( fn.timerID ) {
                            window.clearInterval(timers[label][fn.timerID]);
                            delete timers[label][fn.timerID];
                        }
                    } else {
                        for ( var fn in timers[label] ) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }

                    for ( ret in timers[label] ) break;
                    if ( !ret ) {
                        ret = null;
                        delete timers[label];
                    }
                }

                for ( ret in timers ) break;
                if ( !ret ) 
                    jQuery.removeData(element, this.dataKey);
            }
        }
    }
});

jQuery(window).bind("unload", function() {
    jQuery.each(jQuery.timer.global, function(index, item) {
        jQuery.timer.remove(item);
    });
});
4

2 に答える 2

2

これは、プラグインのメカニズムがどのように機能するかということです。jQuery.fnオブジェクトを独自の関数で拡張することにより、jQuery プラグインを作成します。jQuery.fn オブジェクトに関数を直接追加するか、jQuery.fn.extend() を呼び出します。

これらのプラグイン関数には、常に jQuery オブジェクト (つまり、呼び出された DOM 要素の選択) がthis変数として渡されます。

たとえば、アラートを使用して DOM セット内のアイテム数を表示する jQuery プラグインを作成するとします。

$.fn.showCount = function() { 
   alert("Count = " + this.length); // "this" is a refernce to the jQuery object
}

または(まったく同じです):

// $.fn.extend is just a convenience method for extending the jQuery.fn object
// It's also the same as calling $.extend($.fn, { ... })

$.fn.extend( {
                showCount: function() { 
                        alert("Count = " + this.length);
                }
             });

だからあなたが呼び出すとき:

$("a").showCount();

<a>ドキュメント内のタグの数を知らせるアラートがポップアップ表示されます。

編集

あなたのコードを見た後、私はあなたが何を得ているのか知っていると思います。

jQuery.extend() (jQuery.fn.extend ではない) を使用する場合、REAL プラグインは作成されません。jQuery自体とは関係のない、グローバル関数またはオブジェクトを作成しているだけです。

実際、タイマー プラグインは次のように記述でき、まったく同じことを実行できます。

var timerPlugin = {
       global: [],
        guid: 1,
        dataKey: "jQuery.timer",
        regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
           //...
        }
        // ...
  };

次に (たとえば) jQuery.timer.remove()の代わりにtimerPlugin.remove () を呼び出します。

jQuery.fn オブジェクトの拡張は、jQuery オブジェクトで独自の関数を呼び出せるようにするために行われます。例: $("a").myPlugin()

覚えておくべきことは、jQuery.extend() は jQuery や jQuery プラグインとは何の関係もないということです。これは、jQuery ライブラリによって提供される単なるユーティリティ関数です。

于 2010-01-02T12:15:44.863 に答える
0

プラグインを定義する方法はいくつかあります

$.fn.myFunc=function(opt){

};

$.fn.myOtherFunc=function(opt){

};

と同じです

$.fn.extend({
  myFunc:function(opt){

  },
  myOtherFunc:function(opt){

  }
});
于 2010-01-02T11:58:08.063 に答える