/    Sign up×
Community /Pin to ProfileBookmark

Having trouble with ‘this’

I have the following javascript code – augmented with the dojo library:

[CODE]function theAdminDojoTools() {

this.wireUserDeActivateEvents = function () {
var userDiv = document.getElementById(“userListDiv”);
var deactiveButtons = userDiv.getElementsByClassName(“deactivateUserButton”)
for (var i = 0; i < deactiveButtons.length; i++) {
deactiveButtons[i].onclick = this.deactivateUser;
}
}

this.deactivateUser = dojo.hitch(this, function (evt) {
var UserId = evt.srcElement.dataset.userid;
require([“dojo/request/xhr”], function (xhr) {
var url = “/users/DeactivateUser”
var postData = { id: UserId }
new xhr(url, { method: “POST”, data: postData }).then(this.deactiveUserSuccess(), this.deactiveUserFailure());
});
});

this.deactivateUserSuccess = dojo.hitch(this, function (data) {
alert(“user deactivated.”)
});

this.deactivateUserFailure = function (data) {
alert(“failure deactivate”)
}

var self = this;
}
[/CODE]

The problem I’m having is in the deactivateUser function. When this function is called, in the xhr promise, deactiveUserSuccess is always undefined (as is deactiveUserFailure ? ). It seems that ‘this’ in this context refers to the html element whose click event called deactivateUser .

I’ve tried referring to ‘self’ instead of ‘this’. No success.

I’ve tried removing the various dojo.hitch functions. No success there either.

‘this’ always refers to something other than ‘theAdminDojoTools’.

I have similar functionality in other parts of my app and it works just fine. I can’t help but think I’ve overlooked something.

Any ideas?

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@rootJun 17.2016 — this refers to the object that the function is accessing the object or variable.

you can also pass this as a reference to an object like in a web form to a function.

It is well documented, so you need to know what it is that you don't grasp to get to grips with how this works as a referencing point.
×

Success!

Help @dolot spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.21,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...