views:

81

answers:

3
this
Application.EventManager.on('Click', function(args) { // event listener, args is JSON
    TestAction.getContents(args.node.id, function(result, e) { 
        console.log(result);
        this.add({
            title: args.node.id,
            html: result
        }).show();
    });
});

I'm really struggling with scope and anonymous functions... I want this (on the 1st line) to be the same object as this (on the 5th line)... .call() and .apply() seemed to be the right sort of idea but I don't want to trigger the event... just change it's scope....

For a bit of contexts... the this in question is a TabContainer and TestAction is a RPC that returns content...

Thanks....

+2  A: 

What you need is a variable defined on the outside scope that is set to this:

var that = this;
Application.EventManager.on('Click', function(args) { // event listener, args is JSON
    TestAction.getContents(args.node.id, function(result, e) { 
        console.log(result);
        that.add({
            title: args.node.id,
            html: result
        }).show();
    });
});

Thanks to closures, you can do this (err, that), even inside of a function.

Joey Adams
Beautifully simple... I've wasted too much time on this... many thanks...
Simon
See @bmoeskau answer below for a more beautiful answer.
Upper Stage
A: 

Unfortunately, in an anonymous function, this is the function. You should make the function a member of the object in question and reference it by name.

Eric Mickelsen
+2  A: 

Yes, @Joey's answer does work in terms of generic JS code. However, since you are using Ext JS according to your tags, I will point out that the proper approach is to call the event callback function within the proper scope to begin with since Ext handles passing and setting scope for you. E.g., the Ext way would be (assuming your Application class is using the standard Ext on() function):

Application.EventManager.on('Click', function(args) { // event listener, args is JSON
    TestAction.getContents(args.node.id, function(result, e) { 
        console.log(result);
        this.add({
            title: args.node.id,
            html: result
        }).show();
    });
}, this); // 3rd arg to .on() is scope!
bmoeskau
Even better... let me try and implement this later...
Simon
I think you'll have to add `this` to the scope of the inner method call to `TestAction.getContents` (which seems to be an ExtDirect call) too.
Stefan Gehrig