0

I would like to know how to point this to the selected element (event source) inside .on() method without defining an anonymous event handling function.

For example, in the code bellow, the context for my selected element is document, i.e. $(this) is interpreted as document

$('.nav-item').click(MyFrameworkUtils.navigationBinding($(this), 'arg1', 'arg2'))

However, if wrapped in an anonymous event handler, $(this) is interpreted (desirably) as the selected element.

$('.nav-item').click(function(){
    var source = $(this);
    MyFrameworkUtils.navigationBinding(source, 'arg1', 'arg2');
});
Mandeep Jain
  • 2,304
  • 4
  • 22
  • 38
Lim H.
  • 9,870
  • 9
  • 48
  • 74

2 Answers2

6

You could use this syntax:

$('.nav-item').click({arg1:'arg1', arg2:'arg2'}, MyFrameworkUtils.navigationBinding)

and the function would look like this:

function navigationBinding(event) {
    var source = $(this);
    var arg1 = event.data.arg1;
    var arg2 = event.data.arg2;
}
Robert Fricke
  • 3,637
  • 21
  • 34
1

In your first example, you're passing the result of MyFrameworkUtils.navigationBinding($(this), 'arg1', 'arg2') into your click method. The context of this is therefore the context is the outer scope, which is the document in your case.

With the second example however the scope is the inner function, and as with most events triggered by the DOM, this is the triggering element.

Additionally [possibly unrelated], when calling functions you can define this by using the apply or call methods, as described quite nicely in What is the difference between call and apply?

Community
  • 1
  • 1
Richard
  • 8,110
  • 3
  • 36
  • 59
  • Thanksssss. It makes a lot of sense.. well, Javascript sense. And thanks for suggesting the apply and call functions. – Lim H. Jan 24 '13 at 11:26