*Although I can see the similarities, the question referenced as a duplicate is regarding binding click events to objects within objects via a callback. My question is regarding binding click events to properties of an object. So while similar, I was not able to apply the information in that question to my question; however, I was able to apply the information received here to solve my problem. And lastly, as there are often several ways to solve similar problem, I think the community could benefit by keeping both questions up since two distinctly different solutions are provided to two similar but different questions.
I have a card object with a contstructor that looks something like this...
function cardObj(params){
this.id = params.id;
this.card = document.createElement('div');
this.itemBody = document.createElement('div');
this.footerContainer = document.createElement('div');
this.card.appendChild(this.itemBody);
this.card.appendChild(this.footerContainer);
}
Then I'm trying to prototype some methods because I'm going to have possibly several hundred cards on the page...
cardObj.prototype.toggleDescription = function (){
// do some stuff
};
The problem:
I can't seem to set get onclick to work on any of the object properties. I've tried something like...
(within the cardObj constructor)
this.footerContainer.click = function(){this.toggleDescription();};
And I've also tried (in my programs main program function)...
cardArr[x] = new cardObj(params);
parentDiv.appendChild(cardArr[x].card);
cardArr[x].footerContainer.click = function(){this.toggleDescription();};
And I'm getting various "toggleDescription is not a function" and "this.toggleDescription" is not defined errors.
I'd like to set the click attribute within the object constructor somehow if possible as I'd like to keep this completely modular so I could, for instance, simply copy and paste my cardObj.js file into another program and have it all just work with me only needing to pass some parameters to the constructor. Is this possible? Where am I going wrong?