1

ボイラープレート jquery プラグインのこの一般的な設計パターンに従いましたが、プロトタイプのどこからでもコンストラクター内で特権メソッド this.service() を呼び出すのに問題があります。プロトタイプの初期化だけでなく、プロトタイプ内から this.service() を呼び出すにはどうすればよいですか?

全体として、私がやろうとしているのは、プラグインのこのインスタンス内でのみ影響を受け、変更されるこのプラグインの変数にアクセスできるようにすることです。この変数を別の場所に配置する必要がありますか? 変数は、私のコードでは variableToAccess という名前です。多分私はこれですべて間違っています。ありがとう。

プラグインは次のように呼び出されます

$('article').comment();

ここにプラグインがあります

;(function ( $, window, document, undefined ) {
    // Create the defaults once
    var pluginName = 'defaultPluginName',
        defaults = {
        propertyName: "value"
    };

    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options) ;
        this._defaults = defaults;
        this._name = pluginName;
        var variableToAccess = false;//<----should this be somewhere else?
        this.service = function() {
            variableToAccess = true;
        };
        this.init();
    }

    Plugin.prototype = {
        init: function() {
            Plugin.prototype.doSomething();
        },
        doSomething: function() {
            this.service()//<----doesn't work
        }
    }

    $.fn["comment"] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin( this, options ));
            }
        });
    }

})( jQuery, window, document );
4

1 に答える 1

0

ここで間違っている可能性がありますが、Plugin.prototype.doSomething() を介して doSomething() を呼び出す必要はないと思います。

this.doSomething(); メソッドを呼び出す必要があります。下記を参照してください:

function Plugin( element, options ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options) ;
    this._defaults = defaults;
    this._name = pluginName;
    var variableToAccess = false;
    this.service = function() {
        variableToAccess = true;
    };
    this.init();
}

Plugin.prototype = {
    init: function() {
        this.doSomething();
    },
    doSomething: function() {
        this.service();
    }
};

$.fn.comment = function ( options ) {
    return this.each(function () {
        if ( !$.data(this, 'plugin_' + pluginName) ) {
            $.data(this, 'plugin_' + pluginName,
            new Plugin( this, options ));
        }
    });
 };
于 2012-10-01T17:09:56.953 に答える