2012-01-07 9 views
0

私はjQueryプラグインのためのdo-it-all基本フレームワークの一種に取り組んでいます。私は、jQueryプラグイン/オーサリングのサンプルをhereで見つけ出しました。メソッドとコールバックを持つjQueryプラグイン

(function($){ 
    var methods = { 
    init : function(options) { 
     var defaults = { 
      // place default settings for plugin here 
     } 

     var options = $.extend(defaults, options); 

     return this.each(function(){ 
      var $this = $(this), 
       data = $this.data('PLUGINNAME'); 

      if (! data) { 
      // do more setup stuff here 
      } 
     }); 
    }, 

    destroy : function() { 
     return this.each(function(){ 
     // do stuff to destroy any function binding 
     }) 
    }, 

    update : function(content) { 
     return this.each(function() { 
      //do your update stuff here 
     }) 
    } 
    }; 

    $.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); 

私は今を把握しようとしている作品は、プラグインのコールにコールバック関数を追加する方法です:

は、ここで私は建物だ構造のさらなる簡略版です。私は、このような別のパラメーター必要がありますことを知っている:

$.fn.PLUGINNAME = function(method, callback) { 

を私はそれが私が現在持っているものに基づいて実装については移動するかどうかはわかりません。

+0

このコールバックは何をすべきか、その署名は何ですか? –

+0

コールバックが何をすべきかは関係ありません。おそらく、プラグインが(getJSON呼び出しのような)いくつかのスクリプトを実行してから、ページ上のいくつかの要素を処理するまで待つ必要があるかもしれません。 –

答えて

1

コールバック関数を呼び出すには、.callメソッドを使用できます。

init : function(options, callback) { 
    callback.call(this, options); 

この例では、私はオプションを渡しましたが、必要なものはすべて渡すことができます。

+0

しかし、 'return this.each(function(){' returnを使用すると、プラグインの連鎖性の考え方はどうなるのでしょうか? –

+0

"this"を返す限り、この " コールバックを許可するjQueryのデフォルト関数のいくつかを見ることができます。 –

+0

私の更新メソッドは次のようになりますか? 'update:function(options、callback){ リターンthis.each(関数(){ callback.call(これ、オプション);} )?。 } 'とプラグイン自体に変更がある –

関連する問題