I am switching an app over to RequireJS.
In my app, I detect when a user clicks on an element with a certain class on it.
I use the click event and this.id to get the unique id of the element.
Now that I've moved this function to a module for Require, I only get 'undefined' back for this.id.
I'm guessing the module doesn't have a reference for what was clicked when the function is called.
I also can't seem to pass this.id to the module.
'the use of a keyword as an identifier is invalid'.
So, how do I get the unique ID of the element clicked?
$(document).on('click', '.userSelect', function (myID) {
var retConvo = getConvoID.convoData();
convoID = retConvo.convo;
isGroup = retConvo.group;
console.log("Conversation ID is: " + convoID + " and IsGroup: " + isGroup);
});
and here is the module code it's calling.
define(function() {
return {
convoData: function(myID) {
var userSelected = this.id;
console.log('User Selected ID is: ' + userSelected);
if (userSelected == myID) {
alert("You can't message yourself.");
return false;
} else {
console.log("Selected User ID is: " + this.id);
// change background to show user is selected.
$("div.userSelected").removeClass("userSelected");
$(this).addClass("userSelected");
convoID = this.id;
isGroup = 'N';
console.log("emitting convo users id: " + convoID);
return {
convo: convoID,
group: isGroup
};
}
}
}
});
So, when it get's to this.id above, it is undefined. Worked fine when it was all in one js file.
Thanks for any help and pointers.
A couple of things:
myID
to the convoData
function this
in the function refers to the local this
. If you want it refer to the clicked element, either pass the element as a parameter to the function, or bind it at function call time: var retConvo = getConvoID.convoData(myId).bind(this);
Alternatively, var retConvo = getConvoID.convoData(myId, this);
and then change convoData
to function(myID, element)
and refer to element.id
; ===
instead of ==
in your code - has no bearing on this question per se, but will help you avoid problems down the line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.