开发者

JS Anonymous Scope

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...开发者_如何学C the this in question is a TabContainer and TestAction is a RPC that returns content...

Thanks....


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.


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!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜