How to keep scope in selectPath callback?

Hi

I'm using selectPath in a tree to select a node. If the node doesn't exist, I'd like to add it to the tree. Problem is that selectPath's callback function looses scope. I therefore can't access the tree's root. Or is there a solution?

Closures, context, scope, bound parameters

This has nothing to do with select path. What you should understand is how createDelegate works. It makes sure that when a function is called, it is called with specific parameters and under a specific context (the this keyword). Look at the doc for createDelegate.

The proposed solution works because it ensures that the callback is called from the same context (scope) as what you pass to createDelegate, therefore "this" (the scope or context) is the same in both functions.

In your first attempt, "this" was the window because it is called from a global context (global only means in the context of window, since global variables actually belong to the window object)

So... a trick that may be used is to create a local variable and set it to "this". Then that variable is made available to the inner function (through a closure) without the need to use "this" in your function and get you confused about what the context will be when it's called. However, the createDelegate solution seems more elegant. Just telling you this to add to your bag of tricks.