0

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 as a callback I think, but my question is how I can solve this on a nice way?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Derk
  • 181
  • 2
  • 2
  • 6

3 Answers3

1

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);
    };
}
Seb
  • 24,920
  • 5
  • 67
  • 85
  • Using the global environment to bind the function to a variable is not necessarily a clean solution, however it will work. – Yuval Adam Nov 05 '09 at 16:18
  • @Yuval: that's not global, it's only in the scope of the ApplicationWindow function... – Seb Nov 05 '09 at 16:22
  • @Yuval: if you declare variables with `var` you're setting the scope to the current function only. If you don't, then yes, global scope is used instead. – Seb Nov 05 '09 at 16:22
0

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);
        });
    }
}
Matt Smith
  • 1,221
  • 1
  • 8
  • 20
0

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);
Rob
  • 8,042
  • 3
  • 35
  • 37