0

The code below would invoke a function which adds the clicked name into an array. However, $(this) is calling the app object instead of the clicked text. I'm guessing I can't use $(this) and this in the same function and expect the this to be calling different things. Is there an alternative solution to this?

var App = function () {
this.friends = [];
};

App.prototype.addFriend = function () {
name = $(this).text();
this.friends.push(name); 
}

var app = new App();

$(document).ready(function () {
$(document).on("click", ".user", function () {app.addFriend()});
}
Leo Tsang
  • 27
  • 4
  • Does this answer your question? [this vs $(this)](https://stackoverflow.com/questions/7479282/this-vs-this) – Shubham Dixit Jul 09 '20 at 10:49
  • Pass the event object, and use `$(event.target)` insted of `$(this)`. Or if it's just that value you need to read, `text = event.target.value;`, an extra DOM traversing step is not needed. – Teemu Jul 09 '20 at 10:49

2 Answers2

0

pass event object to function and take the value from it

var App = function () {
this.friends = [];
};

App.prototype.addFriend = function (event) {
name = $(event).target.value;
this.friends.push(name); 
}

var app = new App();

$(document).ready(function () {
$(document).on("click", ".user", function (event) {app.addFriend(event)});
}
Linoy
  • 1,363
  • 1
  • 14
  • 29
0

You can pass the target element of the click event as an argument to addFriend():

App.prototype.addFriend = function (item) {
name = $(item).text();
this.friends.push(name); 
}

var app = new App();

$(document).ready(function () {
$(document).on("click", ".user", function (event) {app.addFriend(event.target)});
}
Divarrek
  • 325
  • 3
  • 11