2

私は jQuery プラグインを作成しており、ソリューションをよりモジュール化するためにいくつかの拡張機能を提供したいと考えています。拡張を実行するための正しい構文があると思いますが、拡張機能でメソッドを呼び出すことができないようです。簡潔にするためにコードのセクションのみを含めましたが、必要に応じてさらに提供できます。どんな助けでも大歓迎です!

メインプラグインにhttp://jqueryboilerplate.com/を使用しており、拡張メソッドを追加するためのこのスタックオーバーフローの回答: jQuery プラグインを拡張する最良の方法

主な jQuery プラグイン

function Plugin( element, options ) {
    this.element = element;

    // jQuery has an extend method which merges the contents of two or
    // more objects, storing the result in the first object. The first object
    // is generally empty as 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() {

        //This line does NOT work
        var id = this.showId();
        console.log(id);

        var toolbar = this.createToolbar(this.options);
        $(this.element).append(toolbar);

        if(this.options.showPalette)
        {
            var palette = this.createPalette(this.options);
            $(this.element).append(palette);
            this.fetchPalette();
        }

        var canvas = this.createCanvas(this.options);
        $(this.element).append(canvas);

    }, .... 

プラグインコンストラクター

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

延長方法

var extensionMethods = {
    /*
     * retrieve the id of the element
     * this is some context within the existing plugin
     */
    showId: function(){
        return this.element[0].id;
    }, ....

jQuery拡張

$.extend(true, $['fn']['workflowEditor'].prototype, extensionMethods);
4

1 に答える 1

0

プラグイン メソッドの呼び出しをサポートしているコードのどこにも、組み込みまたは後で拡張メソッドとして追加されたものはありません。

$(el).workflowEditor('mymethod', ...)jQuery UI が機能するのと同じ方法で呼び出すことができるようにすることが意図されている場合は、おそらく次のものが必要です。

$.fn[pluginName] = function (options) {
    var ns = "plugin_" + pluginName;  // don't repeat yourself...
    if (options instanceof object) {
        return this.each(function () {
            if (!$.data(this, ns)) {
                $.data(this, ns, new Plugin( this, options ));
            }
        });
     } else {
         var args = [].slice.call(arguments, 0);  // copy args
         var method = args.shift();
         return this.each(function() {
             $['fn'][pluginName][method].apply($.data(this, ns), args);
         });
     }
};

Plugin.methodこれは、コンテキストが保持されたPluginオブジェクトであり、引数が引数リストの残りの部分である状態で呼び出す必要があります。

as として呼び出された場合$(el).workflowEditor({ ... })(つまり、オブジェクトをパラメーターとして使用した場合)、以前と同様にプラグインが関連付けられます。

于 2013-05-29T15:43:17.897 に答える