views:

98

answers:

4

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?

A: 

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  A: 

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
Using the global environment to bind the function to a variable is not necessarily a clean solution, however it will work.
Yuval A
@Yuval: that's not global, it's only in the scope of the ApplicationWindow function...
Seb
@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
A: 

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
The library I'm using is jQuery
Derk
A: 

See this answer for an explanation of JavaScript's curious this-binding feature and how to work around it using an explicit closure or function.bind.

bobince