https://www.flickr.com/photos/77818424@N06/
/* pseudocode! */
//subject
class Model {
register(observer){ }
remove(observer){ }
notifyAll() { }
getState() { }
setState(newState){
this.state = newState;
notifyAll(); //updated!
}
}
//observer
class View {
constructor(model) {
this.model = model;
}
notify() {
display(this.model.getState())
}
}
//registrar/middle-man
class Controller {
constructor(model, view) {
this.model = model;
this.view = view;
//register the observer
this.model.register(view);
}
//when user does stuff
userDoAction(){
//process action...
this.model.setState(newState);
}
}
//execute the program
function main() {
let model = new Model();
let view = new View(model);
let ctrl = new Controller(model, view);
ctrl.userDoAction();
}
class View {
constructor(model){
this.model = model;
//view elements
this.button = new Button();
}
setController(controller) {
this.controller = controller;
}
//when button is pressed
performButtonPress(){
//delegate to controller
this.controller.userDoAction();
}
notify() {
display(this.model.getState())
}
//...
}
//registrar/middle-man
class Controller {
constructor(model, view) {
this.model = model;
this.view = view;
view.setController(this); //assign
//observer pattern
this.model.register(view);
}
//when user does stuff
userDoAction(){
//process action...
this.model.setState(newState);
}
}
//execute the program
function main() {
let model = new Model();
let view = new View(model);
let ctrl = new Controller(model, view);
view.performButtonPress();
}
<!-- Which one to load first?! -->
<script src="dist/model.js"></script>
<script src="dist/view.js"></script>
<script src="dist/controller.js"></script>
<script src="dist/index.js"></script>
<!-- one file for all your js needs -->
<script src="dist/bundle.js"></script>
# install dependencies (listed in package.json)
npm install
# global, watch mode
webpack --watch
# installed locally
./node_modules/.bin/webpack --watch
# dev server (auto reload)
webpack-dev-server --inline --open
display() {
let gamebox = $('#game-box');
gamebox.empty(); //clear old display
// make grid of buttons
for(let i=0; i<this.game.size; i++){ //row
let row = $('<div>'); //a row for the button
for(let j=0; j<this.game.size; j++) {
let player = this.game.getPiece(i,j);
if(player === undefined) player = -1;
let button = $('<button class="btn btn-default">' +
this.playerSymbols[player+1] +
'</button>')
button.click((e) => this.handleClick(i,j)); //closure!!
row.append(button);
}
gamebox.append(row);
}
//show winner, if any
let winner = game.getWinner();
if(winner !== undefined){
this.showWinner(winner)
$('button').attr('disabled','disabled'); //disable all the buttons
}
else {
this.showPrompt(); //show prompt for next move
}
}