开发者

OOP in Javascript with callbacks

I want to close my window (just a div with position absolute that is draggable) when I click on the close link

This is my code:

function ApplicationWindow() {
    this.window = $('<div class="window"></div>');
    
    this.create = function create() {
        //.....
        var closeButton = this.window.find('.close');
        closeButton.live('click', this.close);
    }

    this.close = function close() {
        this.window.fadeOut(200);
    };
}

When I click on the close button the close function is executed, but the problem is that I get an error:

"this.window is undefined".

That is because the close function is passed a开发者_Python百科s a callback I think, but my question is how I can solve this on a nice way?


Don't use this. In JS, the reserved word this changes depending on the context so you want to avoid it in this case.

Using a simple variable in scope should solve the problem:

function ApplicationWindow() {
    var theWindow = $('<div class="window"></div>');

    this.create = function create() {
        //.....
        var closeButton = theWindow.find('.close');
        closeButton.live('click', this.close);
    }

    this.close = function close() {
        theWindow.fadeOut(200);
    };
}


like this;

function ApplicationWindow() {
    this.window = $('<div class="window"></div>');

    this.create = function create() {
        //.....
        var closeButton = this.window.find('.close');
        var self = this;
        closeButton.live('click', function() {
            self.window.fadeOut(200);
        });
    }
}


What library are you using? You should be able to bind the function to your object:

this.close = function close() {
    this.window.fadeOut(200);
}.bind(this);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜