5

プロジェクトで作業しているプラ​​グインのベースとして次のコードを使用しています。これは、「ALightweightStart」という見出しの下にあるSmashingMagazineの記事からのものです。

http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

これまでのところ、私の目的には問題なく機能していますが、この記事の残りの部分では、jQuery UIライブラリが必要であると私が想定している、実際には使用したくないjQueryUIウィジェットについて説明します。

/*!
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;(function ( $, window, document, undefined ) {

    // undefined is used here as the undefined global
    // variable in ECMAScript 3 and is mutable (i.e. it can
    // be changed by someone else). undefined isn't really
    // being passed in so we can ensure that its value is
    // truly undefined. In ES5, undefined can no longer be
    // modified.

    // window and document are passed through as local
    // variables rather than as globals, because this (slightly)
    // quickens the resolution process and can be more
    // efficiently minified (especially when both are
    // regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = 'defaultPluginName',
        defaults = {
            propertyName: "value"
        };

    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype.init = function () {
        // Place initialization logic here
        // You already have access to the DOM element and
        // the options via the instance, e.g. this.element
        // and this.options
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin( this, options ));
            }
        });
    }

})( jQuery, window, document );

これにメソッドを追加する必要がありますが、その方法についてはかなりわかりません。

このメソッドは、プラグインがページ上に作成しているもののインスタンスが、コンソールを介して値を使用してメソッドを呼び出すことにより、プロパティを動的に変更できるように機能する必要があります(最終的には、これは他のプロセスを介して発生しますが、コンソールは今のところ良い)。

これを可能にするために上記のコードを修正するにはどうすればよいですか?それとも私は間違った木を吠えていますか?

どんな助けでも大歓迎です。複雑なJavaScriptは、私が恐れているときに暗闇の中で少し迷子になる可能性がありますが、可能な限り「ベストプラクティス」を実行しようとしています。

4

3 に答える 3

12

jQueryのドキュメントでは、メインのプラグインメソッドに文字列を渡してプラグインメソッドを呼び出すことを強くお勧めします。$.fnこれは、プラグインのメソッドによって名前空間が乱雑になるのを防ぐためです。だからあなたはこのようなことをします:

$.fn.yourPlugin = function(options) {
    if (typeof options === "string") {
        //Call method referred to by 'options'
    } else {
        //Setup plugin as usual
    }
};

あなたのパターンでは、あなたはすでにあなたのメソッドを定義するのに最適な場所を持っています:Plugin.prototype。たとえば、changeColorメソッドを追加するには、次のようにします。

Plugin.prototype.changeColor = function(color) {
    $(this.element).css("color", color);
}

の使用に注意してください$(this.element)。これは、Pluginコンストラクターでプロパティelementが定義され、プラグインが適用されている要素がそれに割り当てられているためです。

this.element = element;

これは実際のDOM要素であり、jQueryオブジェクトではないため、jQueryを呼び出す必要があります。

これでメソッドができたので、それを呼び出すメカニズムを追加する必要があります。jQueryドキュメントの推奨事項に従います。

$.fn[pluginName] = function ( options ) {
    return this.each(function () {
        if (typeof options === "string") {
            var args = Array.prototype.slice.call(arguments, 1),
                plugin = $.data(this, 'plugin_' + pluginName);
            plugin[options].apply(plugin, args);
        } else if (!$.data(this, 'plugin_' + pluginName)) {
            $.data(this, 'plugin_' + pluginName,
            new Plugin( this, options ));
        }
    });
};

changeColor次に、次のようにメソッドを呼び出すことができます。

$("#example").defaultPluginName("changeColour", "red");​​​​​​​​​​​​​​​​​​​​​​​​​​​

これが実際の例のフィドルです。メソッド呼び出しコードの周りにチェックを追加して、呼び出している要素でプラグインが実際にインスタンス化されていることを確認することをお勧めします。

于 2012-06-11T10:34:08.140 に答える
0

使用する

Plugin.prototype.reset = function () {

};
Plugin.prototype.destroy = function () {

};

等々。必要な数のオプションを追加します

于 2012-06-11T10:10:25.843 に答える
0

理解しにくい定型文から始めるのではなく、原点から始めるのが最善です。

http://docs.jquery.com/Plugins/Authoring

于 2012-06-11T10:12:24.937 に答える