public
Last active

State pattern with JavaScript and jQuery

  • Download Gist
gistfile1.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var State = function () {};
 
State.prototype.add = function (addButton) {
throw new Error("It needs to be implemented by subclasses");
};
 
var AddOneState = function () {};
AddOneState.prototype = Object.create(State.prototype);
AddOneState.prototype.add = function (addButton) {
var lastInput = addButton.prev().prev();
var newInput = lastInput.clone();
addButton.before(newInput);
addButton.before("<br/>");
};
 
var AddBothState = function () {};
AddBothState.prototype = Object.create(State.prototype);
AddBothState.prototype.add = function (addButton) {
var inputDivs = $(".input_div");
inputDivs.each(function (index, inputDiv) {
var $inputDiv = $(inputDiv);
var addButtton = $inputDiv.find("a.add");
var lastInput = $inputDiv.find("input:last");
var newInput = lastInput.clone();
addButtton.before(newInput);
addButtton.before("<br/>");
});
};
 
var Page = function (state) {
this.state = state;
};
Page.prototype.add = function (addButton) {
this.state.add(addButton);
};
 
var page = new Page(new AddOneState());
 
$("a.add").click(function (e) {
e.preventDefault();
page.add($(this));
});
 
$("input[name='state']").change(function () {
var stateVal = $("input[name='state']:checked").val();
if (stateVal == "one") {
page.state = new AddOneState();
}
else {
page.state = new AddBothState();
}
});
});
</script>
</head>
<body>
<div style="width:100%;">
<div style="float:left; width:50%">
<input type="radio" name="state" checked="checked" value="one">Add one</input>
</div>
<div style="float:left; width:50%">
<input type="radio" name="state" value="both">Add both</input>
</div>
</div>
 
<div class="input_div">
<input type="text" class="title" placeholder="Title" />
<br/>
<a href="" class="add">+Add</a>
</div>
 
<br/>
<br/>
<br/>
 
<div class="input_div">
<input type="text" class="body" placeholder="Body" />
<br/>
<a href="" class="add">+Add</a>
</div>
</body>
</html>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.