1

私はjqueryプラグインのオーサリングに不慣れで、プラグイン内のメソッドが同じプラグイン内の別のメソッドをどのように呼び出すことができるのか疑問に思います。

サンプルコードでは、f1からf2を呼び出そうとしていますが、f2メソッドのthis.each()が原因でjsエラーが発生します。

教えてくれませんか?

ありがとう

編集:f1()およびf2()は、プラグイン$ .pluginName('f1')および$ .pluginName('f2')の外部から呼び出すことができます。

私が欲しいのは、f1()のsommeコードの後に​​f2()を呼び出すことです。

;
(function( $ ){
    'use strict';

    var pluginName = 'pluginName';

    var defaults = {
    };

    var methods = {
        init : function( options ) {
            return this.each(function ( ) {
                var $this = $(this);
                var settings = $.extend({}, defaults, options);
                $this.data(pluginName, settings);
                return $this;
            });
        },

        f1 : function() {
            methods.f2(); // Uncaught TypeError: Object #<Object> has no method 'each' 
        },

        f2 : function() {
            return this.each(function() {

            });
        }
    };

    $.fn[pluginName] = function( 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 exist on jQuery.' + pluginName + '()');
        }
    };

})( jQuery );
4

1 に答える 1

2

これはエラーを示しています。これは、f2()から呼び出したときf1()にjQueryオブジェクトを渡していないf2()ためthis、内部の同じオブジェクトを参照しないf2()ため、機能しないためです。

したがって、f1()このようにコードを変更します

f1 : function() {
            // some code of F1
            this.css('color','red');
            // now call f2
            methods.f2.apply(this,[]); 
        },

this内で何を意味するかを指定していf2()ます。この場合、jQueryオブジェクトを渡します。

実例

.applyの詳細

于 2012-06-12T09:43:25.690 に答える