19

最近、jQueryでクリックイベントをバインドするときに、jQueryショートカットを使用するかどうか、または自分で呼び出しclick()を指定する必要があるかどうかを疑問視しています。.on('click', ...)

.click ()。jQueryの関数は単なるショートカットです。jQueryは、使用されているjQueryのバージョンごとに優先されるメソッドを説明するバックグラウンドですべてを処理するため、私にとっては使用するのが理にかなっています。スクリプトをjQuery1.6->1.7からアップグレードしたとき、すべてのスクリプトがclick()ショートカットからbind()優先on()メソッドに移行したことがわかりました。これだけでも、ショートカットを使用するのに十分な理由のようです。

...でも....

私が非常に尊敬しているTrevorBurnhamは、彼のeBookAsyncJavascriptで次のように述べています

...より強力なバインド/オンを一貫して使用することを好む)(クリックよりも)

それは私を混乱させ、bind/onを使用することが「より強力」である理由を疑問に思いました。

jQueryでショートカットを持つイベントをバインドするときのベストプラクティスは何だと思いますか?ショートカットを使用しますか、それとも自分で行いますか?

4

2 に答える 2

47

I think it has to do with personal preference and code readability more than anything.

As far a more powerful goes .on lets you delegate events while shortcuts always operate on the element directly. For example $('body').on('click', '.button', function(){}); will work for every .button element even those added after the fact with ajax or otherwise. While the shortcut cannot do this $('.button').click(function(){}); is the only way to add a listener to .button and does not feature delegation, so .button elements added later will not have this binding.

Direct un-delegated events (like shortcuts) on multiple elements is also slightly less efficient then delegated events on a parent object. For example: lets say there are 15 .button elements on the page, $('.button').click(... will loop through all 15 elements and add an event listener to each; however $('#parentElem').on('click', '.button', ... will simply attach a single event listener to #parentElem that checks on the target, so one attach and one listener, vs a loop and 15 listeners.

And finally, .on has the advantage of allowing you to attach a function to an element from multiple events, which is not possible with shortcuts, for example: $('.button').on('click mouseover keyup', ... the function will trigger with click, mouseover or keyup!


Lets again say there are 15 .button elements in a div called #parent

Shortcut handler:

 $('.button').click(turnRed);
 $('.button').mouseover(turnRed);
 $('.button').keyup(turnRed);

 function turnRed(){
      $(this).css('color','red');
 }
  • 4 jQuery objects created (yes I know you could cache it to 2 objects but this is an example)
  • 3 element loops of 15 each, so jQuery hits elements here 45 times and attaches listeners
  • 45 total event listeners
  • future .button elements added to the scene do not turnRed

.on handler:

 $('#parent').on('click mouseover keyup', '.button', turnRed);

 function turnRed(){
      $(this).css('color','red');
 }
  • 2 jQuery objects created
  • No element loop, so jQuery hits elements once
  • 3 total event listeners
  • future .button elements add to the scene will in fact turnRed

Here .on clearly has the advantage


If your situation is simpler than this, then the advantage of .on may not make a difference to you, and the shortcut may be preferred as its more readable.

$('#button').click(... is nearly identical to $('#button').on('click', ... (see @Fabrício Matté's answer) and if we just want to add one listener to one event, the .on's power is a moot point.

Personally because there are times when I want the advantage of .on I always use .on just to be consistent.

于 2012-07-19T00:13:49.593 に答える
1

ソースをざっと見て、関数呼び出しが実際に何をするかを自分で確認できます。

jQuery オブジェクトの内部extend(3754 行目) では、jQuery は 3909 行目でこれらすべてのメソッド名を反復処理します。

ぼかし フォーカス focusin focusout ロード サイズ変更 スクロール アンロード クリック dblクリック マウスダウン マウスアップ マウスムーブ マウスオーバー マウスアウト マウス入力 マウス変更 選択 送信 キーダウン キープレス キーアップ エラー コンテキストメニュー

.onこれらのメソッドが呼び出されたときにセレクター属性を渡さずに、指定されたメソッドのメソッドを呼び出す短縮メソッドを作成します (3921 行目):

this.on( name, null, data, fn )

これは、イベントの委任効果がないことを意味します。


jQuery でショートカットを持つイベントをバインドする際のベスト プラクティスは何ですか? ショートカットを使用しますか、それとも自分で行いますか?

呼び出しの唯一の違い

$(selector).eventname(function(){...})

$(selector).on('eventname', function(){...})

省略形のメソッドには、別の関数呼び出しのオーバーヘッドがあります (これはごくわずかです)。

更新:custom:-event-alias Grunt を使用して jQuery のカスタム ビルドを作成する場合、省略形のメソッドは、さらに小さなビルドのパラメーターを使用して除外できます(ドキュメントはこちら)。ただし、個人的には CDN ビルドに固執する傾向があります。


イベントの委任がどのように機能し、どのような場合に優先されるかについては、ドキュメント@Fresheyeball の回答を確認してください。

于 2012-07-19T00:46:10.797 に答える