Sorry for the poor title, hard to explain this without showing the code.
I have a javaScript class called Coupon that has a function that basically opens up a fancyBox and displays the contents of that coupon object (its dynamic).
Like so
function CouponPopup( id, title, barcodeUrl, expirationDate, description ) {
this.coupondId = id;
this.couponContainer = document.createElement('div');
this.couponTitle = document.createElement('h2');
this.couponPrizeName = document.createElement('h3');
var self = this;
// More vars, etc. . .
// assemble the coupon
this.couponContainer.appendChild(this.couponTitle);
this.couponContainer.appendChild(this.couponPrizeName);
this.couponContainer.appendChild(this.couponRevealDetails);
this.couponContainer.appendChild(this.couponBarcode);
this.couponContainer.appendChild(this.couponExpirationText);
this.couponContainer.appendChild(this.couponPrintButton);
this.show = function ( event ) {
$.fancybox(self.couponContainer);
}
}; // end class CouponPopup
Now, in a the code calling this, I am trying to make a link - that when it is clicked will call the show function on the right instance of CouponPopup.
for (var i = 0; i < dataLength; i++) {
if (data.type === "coupon") {
var couponId = "coupon_" + i;
// right now, my coupon will be on global scope.
myCoupon = new CouponPopup( couponId,
data.rewards[i].prize_name,
data.rewards[i].url,
data.rewards[i].expirationdate);
rewardInfo = '<a id="' + couponId + '" onclick="myCoupon.show( event )">View Coupon</a>';
}
}
rewardInfo eventually gets appended to a the page - and looks fine.
However, when I click on it, since myCoupon is on the globalScope - the fancyBox that is shown is always the last coupon that is created.
If I try to put myCoupon on the local scope (adding the var keyword), I get an JS error saying that myCoupon is undefined when its added to the onClick handler of the link.
What I want to do is make myCoupon a local variable and still have this work - so the onClick event of the link is tied to the specific instance of myCoupon
What is the best way to do this? I have a hack working, but its a hack and I really don't like needing to use global variables in my code if I can help it.
Having a brain fart on this one, so any help is appreciated!
Looking for an old-school ES5 solution.