Skip to content

Instantly share code, notes, and snippets.

@Kedrigern
Last active December 24, 2015 07:09
Show Gist options
  • Save Kedrigern/6761669 to your computer and use it in GitHub Desktop.
Save Kedrigern/6761669 to your computer and use it in GitHub Desktop.
Dices is really small app, which show using of knockout.js
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Dices</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="author" content="Ondřej Profant" />
</head>
<body>
<form data-bind="submit: cast">
<fieldset>
<dl>
<dt>Number of dices</dt>
<dd><input type="number" data-bind="value: repetition"></input></dd>
<dt>Dice type</dt>
<dd><select data-bind="options: types, value: selectType"></select></dd>
<dt>Note</dt>
<dd><input data-bind="value: note"></input></dd>
</dl>
<button type="submit">cast</button>
</fieldset>
<fieldset>
<legend>Results</legend>
<select multiple="multiple" data-bind="options: history" >
</select>
</fieldset>
</form>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js'></script>
<script>
function Cast(type, repetition, note) {
this.sum = 0;
this.results = [];
this.note = note || "";
this.type = type;
for (var i = 0; i < repetition; i++) {
var r = Math.floor(Math.random() * this.type) + 1;
this.sum += r;
this.results.push(r);
};
}
Cast.prototype.toString = function() {
return "Type: " + this.type +
", Sum: " + this.sum +
", Casts: " + this.results.join() +
", Note: " + this.note ;
}
function Model() {
this.history = ko.observableArray([]);
this.types = [4, 6, 12, 20];
this.selectType = this.types[0];
this.repetition = 1;
this.note = "";
this.cast = function() {
this.history.push(new Cast(this.selectType, this.repetition, this.note));
}.bind(this);
}
ko.applyBindings(new Model());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment