Created
August 11, 2014 01:34
-
-
Save kotaroito/61cc85cd222ce8ca07cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div> | |
<form id="print-form"> | |
<p> | |
<input type="radio" name="color" value="red">red | |
<input type="radio" name="color" value="blue">blue | |
<input type="radio" name="color" value="black" checked>black | |
</p> | |
<input id="print-text" type="text" name="text"> | |
<button>print</button> | |
</form> | |
<hr> | |
<div id="print-area"> | |
test | |
</div> | |
</div> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var PrintJob = function(color, content) { | |
var job = Object.create(PrintJob.prototype); | |
job.color = color; | |
job.content = content; | |
return job; | |
}; | |
PrintJob.prototype = { | |
execute: function(place){ | |
var elm = document.createElement('p'); | |
elm.style.color = this.color; | |
elm.innerHTML = this.content; | |
document.getElementById(place).appendChild(elm); | |
} | |
}; | |
var Printer = function(placeId) { | |
var p = Object.create(Printer.prototype); | |
p.placeId = placeId; | |
p.jobs = []; | |
return p; | |
}; | |
Printer.prototype = { | |
addJob: function(job){ | |
this.jobs.push(job); | |
}, | |
run: function() { | |
var that = this; | |
this._interval = setInterval(function() { | |
if ( that.jobs.length > 0) { | |
var job = that.jobs.shift(); | |
job.execute(that.placeId); | |
} | |
}, 1000); | |
} | |
}; | |
(function() { | |
var printer = Printer('print-area'); | |
printer.run(); | |
var btn = document.querySelector("#print-form button"); | |
btn.addEventListener('click', function(e) { | |
e.preventDefault(); | |
var radios = document.getElementsByName('color'); | |
var color; | |
for (var i = 0; i < radios.length; i++) { | |
if (radios[i].checked) { | |
color = radios[i].value; | |
break; | |
} | |
} | |
var text = document.getElementById('print-text'); | |
if (text.value) { | |
var job = PrintJob(color, text.value); | |
printer.addJob(job); | |
} | |
}, false); | |
btn = null; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment