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?

3 Answers 3

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);
    };
}
Sign up to request clarification or add additional context in comments.

3 Comments

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

Comments

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);

1 Comment

The library I'm using is jQuery

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.