1

jQuery はクラスのようなモデルで動作するように設計されていないことは知っていますが、基本クラスを拡張できるようにすることで、私のニーズに完全に適合することができます。

私は次のことをすることから始めました:

jQuery.myBase = {
    foo: 'bar',
    bar: function() { ... }
}

jQuery.fn.myPlugin = function() {
   $.extend( this, jQuery.myBase, {
       oof: 'rab',
       rab: function() { ... }
  }
}

すべて正常に動作し、. 経由で基本メソッドとプロパティにアクセスできますthis。それは、イベント ターゲットを に適用する jQuery イベント ハンドラ (など) のようなものを追加しようとするまでですthis

したがって、次のようになります。

jQuery.myBase = {
    bar: function() { ... }
}

jQuery.fn.myPlugin = function() {
   jQuery.extend( this, jQuery.myBase, {
       init: function() {
           jQuery('#someEl').click( this.onClick );
       },

       onClick: function(e) {
           // this now references the element I bound the event to (<div id="someEl" />)
           // so the following doesn't work
           this.bar();
       }
  }
}

jQuery で動作するクラスの作成と継承 ( John Resig のものDUIなど) のいくつかを見つけましたが、同じ問題が発生します。

thisでは、これらの状況でオリジナルに到達するにはどうすればよいでしょうか?

更新:イベント ハンドラー (など) は、jQuery.myBaseまたはプラグイン自体のいずれかにある可能性があります。

4

4 に答える 4

2

適切なスコープでそれへの参照が必要です。

jQuery.fn.myPlugin = function() {
   var $this = this;  // Scope it up!
   jQuery.extend( this, jQuery.myBase, {
       init: function() {
           jQuery('#someEl').click( this.onClick );
       },

       onClick: function(e) {
           $this.bar();
       }
  }
}
于 2009-10-09T21:13:34.050 に答える
0

私がこれを行うことを考えた唯一の方法は、私があまり好きではないため、質問をすることですが、次の方法です。

jQuery.myBase = {
    bar: function() { ... }
}

jQuery.fn.myPlugin = function() {
   jQuery.extend( this, jQuery.myBase, {
       init: function() {
           var self = this;
           jQuery('#someEl').click( function(e) {
                this.onClick.apply( self, arguments );
           };
       },

       onClick: function(e) {
           // this works
           this.bar();
       }
  }
}
于 2009-10-09T21:12:33.027 に答える
0

別の代替手段は、この質問bind()で指摘されているように、関数を持つプロトタイプの方法に従うことです(実際には私の他の答えと同じですが、よりクリーンな方法で行います)。

if (!Object.bind) {
    Function.prototype.bind= function(owner) {
        var that= this;
        var args= Array.prototype.slice.call(arguments, 1);
        return function() {
            return that.apply(owner,
                args.length===0? arguments : arguments.length===0? args :
                args.concat(Array.prototype.slice.call(arguments, 0))
            );
        };
    };
}


jQuery.fn.myPlugin = function() {
   jQuery.extend( this, jQuery.myBase, {
       init: function() {
           jQuery('#someEl').click( this.onClick.bind( this ) );
       },

       onClick: function(e) {
           this.bar(); // this works
       }
  }
}
于 2009-10-09T22:05:43.913 に答える
0

コメントによると、1.3.3の一部であるはずのjQueryでこれに対処しているようです

于 2009-10-09T22:15:26.813 に答える