-
8 Aug 2007 7:52 AM #1
How to keep scope in selectPath callback?
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?
Here's what I've been trying to do:
The callback is executed, but getRootNode() fails, as this. is the window. What can I do?Code:this.selectPath(target, null, function(success, selNode){ if (!success) { root = this.getRootNode(); root.appendChild(new Ext.tree.AsyncTreeNode({ id: 'xy', text: 'xy' })); } });
Michael
-
8 Aug 2007 10:59 AM #2
I'm not really familiar with selectPath, but I think createDelagate will do the trick
Code:this.selectPath(target, null, function(success, selNode){ if (!success) { root = this.getRootNode(); root.appendChild(new Ext.tree.AsyncTreeNode({ id: 'xy', text: 'xy' })); } }.createDelagate(this));
-
8 Aug 2007 12:43 PM #3
Hi Rich
Perfect! Thanks a lot. Where could I have found documentation about this? I do not even know yet where it's defined...
Michael
-
8 Aug 2007 1:51 PM #4
-
8 Aug 2007 2:13 PM #5
Closures, context, scope, bound parameters
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.
Example
There's a lot more that can be said about this. You're welcome to ask any questions if you are intrigued. Let me know if this is too confusing (and tell me what's confusing).Code:var me = this; this.selectPath(target, null, function(success, selNode){ if (!success) { root = me.getRootNode(); root.appendChild(new Ext.tree.AsyncTreeNode({ id: 'xy', text: 'xy' })); } });
--Juan
-
8 Aug 2007 11:33 PM #6
Juan/evant - thanks a lot for your pointers and help. I really appreciate the fast responses.
Michael


Reply With Quote