0

私は、init、close、open 関数を含む単純なプラグインを持っています。このプラグインを呼び出す html テンプレートの配列があります。特定のテンプレートについてのみ、このプラグインに少し異なる動作をさせたいと思います。たとえば、open 関数に別のクラスを追加し、閉じたときに同じクラスを削除します。それを行うエレガントな方法は何ですか?HTML の ID を見つけて、同じプラグイン内の open 関数と close 関数内で if else を実行する必要がありますか、それともより良い方法がありますか?

;(function ($, window, document, undefined) {

    function Plugin(element, options) {
            Window = this;
            this.element = element;
            this._name = pluginName;
            this.init(element);
        }

    Plugin.prototype = {
            init: function(element) {
     },
    close:function(e){
    //removes a class and hides the element
    },
    open:function(element){
    //adds a class and shows the element
    }

    }
//Extend Global jQuery (where we actually add the plugin!)
    $.fn[pluginName] = function (options) {
        plugin = $.data(window, 'plugin_' + pluginName);
        if (!(plugin instanceof Plugin)) {
            $.data(window, 'plugin_' + pluginName,
            plugin = new Plugin( this, options ));
        }
        return $Extend(this).each(function () {
            $.data(this, 'plugin_' + pluginName, plugin);
        });
    };

}(jQuery, window, document));
4

2 に答える 2

0

optionsプラグインに渡すパラメータにオプションのオブジェクトを追加することで、初期化設定を処理します。

基本的に、options関連するすべての初期化メソッドがパラメータにアクセスできることを確認してから、次のようにします。

open: function(element){
var initClass = options.initClass || "DEFAULTVALUE";
 //adds "initClass" as a class and show the element
}

|| 「options.initClass」が存在しない場合は、デフォルトで次の値を指定するという簡単なトリックです。あなたは||についてもっと学ぶことができます ここ

于 2012-12-28T20:39:48.730 に答える
0

オプションのセットがある場合:

MyPlugin.options = {
    width: 200,
    height: 500,
    add: function () { 
        alert("add was called"); 
    },
    delete: function () { 
        alert("delete was called");
    }
};

プラグインにオプションを渡すと、デフォルトをオーバーライドできます。

function MyPlugin(options){
    options = $.extend({}, MyPlugin.options, options);

    options.add();
}

プラグインのインスタンスを作成するたびに、オプションを設定して 1 つ以上のプロパティをオーバーライドできます。

var plugin = new MyPlugin({
    width: 100,
    add: function () {
        alert("My add was called!");
    }
});

前のコードでは、「My add was called!」というアラートが表示されます。

于 2012-12-28T20:45:55.187 に答える