0

マップをインスタンス化するプラグインを作成しています。マップは、地球上の別の場所に移動する機能を提供します。

スクリプトはマップをうまく作成します。ただし、コールバックで別のプラグインによって使用されるように、要素の関数を「タック」することはできません。

これが私が試したアプローチです。プラグイン:

(function($){
  $.fn.mapDo(options){
    map = new BlahMap(this.get(0));

    this.moveTheMap = function(place){
      map.moveItToThat(place);
    }; // nope.
  }
})(jQuery);

次に、ビューで:

$(map).mapDo();

$(otherElement).otherControl({
  callback: function(place){
    $(map).moveTheMap(place); // moveTheMap is not there on $(map)!
  }
};

質問

可能であれば、マップjQueryまたはDOM要素に関数を追加するにはどうすればよいですか?そうでない場合、どうすればそのような機能を提供できますか?

さらに重要なことに、私はここで物事をそのように分離することによって正しい道を進んでいますか?私はJavascriptの初心者ですが、コンポーネントを分離したまま、これらのタスクは通常どのように実行されますか?

それは私がとった刺し傷ですが、より一般的には、連鎖性を維持しながらjQueryプラグインから物事を出力するという概念に苦労しました。この場合、私がやろうとしているのは、プラグインからコールバックを出力することです。このコールバックは、実行の後半で呼び出された要素で機能します。

4

2 に答える 2

1

mapwith.dataメソッドを保存できます。

(function($){
  $.fn.mapDo = funciont(options) {
    this.data('map', new BlahMap(this.get(0)));
    return this;
  };
  $.fn.moveTheMap = function(place) {
      var map = this.data('map');
      if (map) {
         map.moveItToThat(place);
      }
      return this;
  };
})(jQuery);
于 2012-08-02T09:10:07.490 に答える
1

プラグインは通常、jQueryプロトタイプに1つのメソッドのみを追加し、プラグインのインスタンスへのメソッド呼び出しは文字列を使用して行われます。

(function($) {
    $.fn.mapDo = function(options) {
        var args = [].slice.call(arguments, 1); //Get all the arguments starting from 2nd argument as an array
        return this.each(function() {
            var $this = $(this),
                instance = $this.data("map-instance");
            if (!instance) {
                $this.data("map-instance", (instance = new BlahMap(this, options)));
            }
            if (typeof options == "string") {
                instance[options].apply(instance, args);
            }
        });
    };
})(jQuery);

$(elem).mapDo( "moveTheMap", place ); //This would also instantiate the plugin if it wasn't instantiated

これが実際の動作を示すjsfiddleです。

http://jsfiddle.net/X8YA8/1/

于 2012-08-02T09:10:20.067 に答える