Hey all, was wondering if someone could lend me a little javascript voodoo with this problem…
The code below, includes 2 methods set up as onclick event handlers (increaseCurrentSkill, decreaseCurrentSkill) for a button input in the page itself. I want the event handler to understand properties of the ZAGOR object… i.e, I want a click on the button to increase or decrease the property of the ZAGOR object…
The code I have works OK, but referring to an object instance name from within a method of the object’s ‘class’ is obviously a bit kludgey… Using ‘this. currentSkill += 1’ doesn’t work because currentSkill isn’t a property of the button itself, but ‘ZAGOR.currentSkill += 1’ does work because I’m referring to an instance of my object…
Kind of hard for me to explain exactly, but hopefully you’ll see what I mean! Here’s the code:
var ZAGOR = {
requiredElements: [
'initial_skill',
'current_skill',
'increase_skill',
'decrease_skill'
],
d6: function() {
return Math.floor(Math.random() * 5) + 1;
},
checkObjects: function() {
if(!document.getElementById) return false;
var i;
for(i in this.requiredElements) {
if(!document.getElementById(this.requiredElements*)) return false;
}
return true;
},
storeElementReferences: function() {
if(this.checkObjects) {
this.initial_skill = document.getElementById('initial_skill');
this.current_skill = document.getElementById('current_skill');
this.increase_skill = document.getElementById('increase_skill');
this.decrease_skill = document.getElementById('decrease_skill');
}
},
assignEventHandlers: function() {
this.increase_skill.onclick = this.increaseCurrentSkill;
this.decrease_skill.onclick = this.decreaseCurrentSkill;
},
setInitialSkill: function() {
this.initialSkill = this.d6() + 6;
this.currentSkill = this.initialSkill;
this.initial_skill.firstChild.nodeValue = this.initialSkill;
this.current_skill.firstChild.nodeValue = this.currentSkill;
},
increaseCurrentSkill: function() {
if(ZAGOR.currentSkill < ZAGOR.initialSkill)
ZAGOR.currentSkill += 1;
ZAGOR.current_skill.firstChild.nodeValue = ZAGOR.currentSkill;
},
decreaseCurrentSkill: function() {
if(ZAGOR.currentSkill > 0)
ZAGOR.currentSkill -= 1;
ZAGOR.current_skill.firstChild.nodeValue = ZAGOR.currentSkill;
}
};
window.onload = function() {
ZAGOR.storeElementReferences();
ZAGOR.assignEventHandlers();
ZAGOR.setInitialSkill();
}