This project is read-only.

alternative for "this" to access outer scope AND inner function scope?

Topics: Language Specification
Oct 18, 2013 at 2:22 PM
I have a problem with the either-or-usage of the keyword "this", because sometimes you need the outer scope AND also the inner scope "this":
class Blabla{

private selectNode(node: JQuery) {...}

// will not work: second "this" references the wrong object
$(".treeview_node").click(() => {

// will also not work: first "this" references the wrong object
$(".treeview_node").click(function() {

My workaround now is to take the second option and define explicetly outside a reference to "this" of the class. (like you would do in vanilla javascript)

Is there a more elegant solution?
Oct 18, 2013 at 4:12 PM
The problem, as you've probably realised, is that it's not possible to get "this" to refer to two separate things.

However, I believe you can get hold of the DOM element with the currentTarget property of the event object.

$(".treeview_node").click((event) => {
Oct 20, 2013 at 9:19 PM
Thanks! I should have read the JQuery API more deeply :-)

But this solution will only work for JQuery events, right? A general approach is to introduce a variable for the outer scope manually.

Is this correct?
Oct 21, 2013 at 4:14 PM
Edited Oct 21, 2013 at 4:50 PM

Another approach for this particular case is the following:

var $redundantLib = $(".treeview_node");

$ event => {

This is more optimal, because only one JQuery wrapper is created.

The general approach, I would think, is really a question of locating the object that provides the "this" context for the inner scope; it's normally not too far away.

Edit: Reading your question again, no currentTarget is not specific to JQuery events. It's part of the spec, although its implementation in IE < 9 is suspect.