Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function objects, this keyword points to wrong object

I've got a problem concerning the javascript "this" keyword when used within a javascript functional object. I want to be able to create an object for handling a Modal popup (JQuery UI Dialog).

The object is called CreateItemModal. Which i want to be able to instantiate and pass some config settings. One of the config settings. When the show method is called, the dialog will be shown, but the cancel button is not functioning because the this refers to the DOM object instead of the CreateItemModal object.

How can I fix this, or is there a better approach to put seperate behaviour in seperate "classes" or "objects". I've tried several approaches, including passing the "this" object into the events, but this does not feel like a clean solution.

See (simplified) code below:

function CreateItemModal(config) {
    // initialize some variables including $wrapper
};

CreateItemModal.prototype.show = function() {
    this.$wrapper.dialog({
        buttons: {
            // this crashes because this is not the current object here
            Cancel: this.close
        }
    });
};

CreateItemModal.prototype.close = function() {
    this.config.$wrapper.dialog('close');
};
like image 366
Rody Avatar asked Jan 23 '23 09:01

Rody


1 Answers

You need to create a closure to trap the this context, I tend to use an anonymous function to do this as follows:-

CreateItemModal.prototype.show = function() {
    this.$wrapper.dialog({
        buttons: {
            // this crashes because this is not the current object here
            Cancel: (function(self) {
              return function() { self.close.apply(self, arguments ); }
            })(this);
        }
    });
};
like image 98
AnthonyWJones Avatar answered Feb 06 '23 14:02

AnthonyWJones