0

Is there a way to proxy "this" but also still have access to the "this" of the context you are now within? I typically set this to self but I was curious if there was a way to have two contexts while using $.proxy.

For example...

$('.something').on('click', $proxy(function() {
  // this = proxied this
  // $(this) needs to equal .something
}, this));
besh
  • 35
  • 1
  • 5
  • Duplicate of [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Felix Kling Nov 12 '15 at 19:06
  • I wouldn't say that this is a duplicate since I specifically want to know how to manage two contexts using jQuery's proxy. – besh Nov 13 '15 at 21:59

2 Answers2

1

Obviously this cannot magically refer to two different values.

You don't necessarily have to bind the outer this, there are other ways to access its value: How to access the correct `this` context inside a callback?.

If you want to use $.proxy though, you can use event.currentTarget to access the element (which would normally be referred by this):

$('.something').on('click', $proxy(function(event) {
    $(event.currentTarget).whatever()
}, this));
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks for the answer and the additional info. I updated my question to reflect that I was curious if there was a way to do it with $.proxy despite there being potentially better alternatives. – besh Nov 12 '15 at 19:05
  • Well, in that case your question is a duplicate of http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback, which I linked as well and lists all the possible ways to refer to `this`. Or maybe I misunderstand your comment. – Felix Kling Nov 12 '15 at 19:05
1

Unfortunately, you can't do it without a wrapper function. But why not instead saving the outer this outside and then use in inside the function?

var self = this;
$('.something').on('click', function() {
    self.doSomething();
    // this == element
});

Also, in that case, since you are in an event handler, you can acces the element inside the  event object since this === event.currentTarget. So you can use something like this :

$('.something').on('click', $proxy(function(e) {
  // this = proxied this
  // $(e.currentTarget) equal to .something
}, this));
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • I should update my question. I typically do var self = this but was curious if there was a way to do it using proxy. Your answer seems to be the best way to achieve this. Thanks! – besh Nov 12 '15 at 19:01