Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling one method from another under same js object [duplicate]

Tags:

javascript

I wrote some js:

var folersTreeMgr = {

    sendDeleteFolderRequestAndUpdateFoldersTree: function () {
       ...

        } else {
            createAjaxRequest("Manager/DeleteLocation", {
                'locationId': folder_minimal_descriptor.locationId
            }).done(function (isSucceeded) {

                if (isSucceeded) {

                    folersTreeMgr.deleteFolderInFoldersTree(); // works
                    this.deleteFolderInFoldersTree(); // doesn't work
                    deleteFolderInFoldersTree(); // doesn't work
                }

                //TODO: else: error
            });
        }
    },


    deleteFolderInFoldersTree: function () {
        $("#jstree").jstree("remove", null);
    }
};

why do I get "missing function" error

like image 743
Elad Benda Avatar asked May 12 '26 06:05

Elad Benda


1 Answers

Because you're using this inside a callback, where it has different meaning.

You can referene the outer this in a variable, then use that in the callback.

var folersTreeMgr = {

    sendDeleteFolderRequestAndUpdateFoldersTree: function () {

       var self = this;  // cache it

       ...

        } else {
            createAjaxRequest("Manager/DeleteLocation", {
                'locationId': folder_minimal_descriptor.locationId
            }).done(function (isSucceeded) {
                if (isSucceeded) {
                   self.deleteFolderInFoldersTree(); // works
                }
            });
        }
    },
    deleteFolderInFoldersTree: function () {
        $("#jstree").jstree("remove", null);
    }
};

Or use $.proxy to keep the this value...

createAjaxRequest("Manager/DeleteLocation", {
    'locationId': folder_minimal_descriptor.locationId
}).done( $.proxy(function (isSucceeded) {
    if (isSucceeded) {
       this.deleteFolderInFoldersTree(); // works
    }
},this) );

This'll return a function that has the second argument to $.proxy bound to the function passed as the first argument.

like image 192
user1106925 Avatar answered May 13 '26 21:05

user1106925



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!