Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  162] [ 5]  / answers: 1 / hits: 15868  / 11 Years ago, fri, february 14, 2014, 12:00:00

So I can't quite figure out why the variable this.tasks becomes undefined inside of the add event listener I have inside of my goal object. I have a feeling it might have something to do with asynchronous programming(which I still don't fully understand). Sorry I'm a bit of a JS noob, but if you guys could explain to me what I'm doing wrong and what might be a better solution that would be awesome! Thanks.



function Goal(name) {
this.gDiv = document.createElement('div');
this.name = name || goal;
this.tasks = document.createElement('ul');
//Sets the styling and content and adds it to the parent element
this.initialize = function() {
this.gDiv.className = default;
this.gDiv.setAttribute(id, this.name);
this.gDiv.innerHTML = this.name;
elem.appendChild(this.gDiv);

this.gDiv.parentNode.insertBefore(this.tasks, this.gDiv.nextSibling);
this.tasks.style.display = none;


};
//Creates a list underneath the a dive associated with the Goal object
this.addTask = function(task) {
var newLi = document.createElement('li');
newLi.innerHTML = task;
this.tasks.appendChild(newLi);
};

this.gDiv.addEventListener('click', function(){
alert(this.tasks);
});

}


Thank you guys! You all answered my question! I'd been scratching my head at this for a while. Kudos to you all!


More From » callback

 Answers
23

The scope changes when you enter that anonymous closure and 'this' changes. You can hack around it by doing



var self = this;


And then using self in place of this (eg):



function Goal(name) {
var self = this;

/* ... */

this.gDiv.addEventListener('click', function(){
alert(self.tasks);
});


If you're using jQuery you could do something nicer:



this.gDiv.addEventListener('click', $.proxy(function() {
alert(this.tasks);
}, this));


Either way works just fine.



EDIT: In ES6, arrow functions can be used instead as they don't bind their own this, so it becomes even simpler:



this.gDiv.addEventListener('click', () => {
alert(this.tasks);
});

[#72532] Wednesday, February 12, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
raveno questions
;