Meeting 13
User Interface
13.1 Homework Discussion
Professor: Did you succeed in connecting your generator to the user interface?
Maria: Yes, we did. We started b y reshaping our generator from page 205 into an
object class. This is the code:
var MathWorksheet = function() {
this.equation = null;
this.solution = null;
this.operator = null;
this.maxVal = null;
};
MathWorksheet.prototype.setOperator = function(op) {
this.operator = op;
};
MathWorksheet.prototype.setMaxVal = function(val) {
this.maxVal = val;
};
MathWorksheet.prototype.getEquation = function() {
return this.equation;
};
MathWorksheet.prototype.getSolution = function() {
return this.solution;
};
MathWorksheet.prototype.generate = function() {
var firstOper = Math.round(Math.random() * this.maxVal);
var secondOper = Math.round(Math.random() * this.maxVal);
var tmp;
245
switch (this.operator) {
case "+":
this.solution = firstOper + secondOper;
break;
case "-":
if (firstOper < secondOper) {
tmp = firstOper;
firstOper = secondOper;
secondOper = tmp;
}
this.solution = firstOper - secondOper;
break;
case "*":
this.solution = firstOper * secondOper;
break;
case "/":
if (secondOper == 0) {
secondOper++;
}
tmp = firstOper * secondOper;
this.solution = firstOper;
firstOper = tmp;
}
this.equation = firstOper + this.operator + secondOper + "="
};
Professor: There’s nothing to discuss here, I guess. What a bout the second part? How
did you connec t the generator to the HTML that I gave you?
Mike: We needed to call the getElementByID () method many times so we d ecided
to make the code a bit shorter by d efining the next w rapper function:
var getElement = function(id) {
return document.getElementById(id);
};
Using this function, we produc ed the following code:
window.onload = function() {
var ws = new MathWorksheet();
var score = 0;
ws.setOperator("*");
ws.setMaxVal(10);
ws.generate();
getElement("eq0-label").innerHTML = ws.getEquation();
getElement("submit").onclick = function() {
if (ws.getSolution() == parseInt(getElement("eq0").value)) {
score++;
}
246 Meeting 13. User Interface
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.24