Haymaker MVC Example
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.0.0.js"></script>
<div id='inputSection'>
<p>
<label for='txtFirstName'>First Name:</label>
<input type='text' id='txtFirstName' name='txtFirstName' data-bind='value: firstName, valueUpdate: "afterkeydown"' />
</p>
<p>
<label for='txtLastName'>Last Name:</label>
<input type='text' id='txtLastName' name='txtLastName' data-bind='value: lastName, valueUpdate: "afterkeydown"' />
</p>
</div>
<div id='outputSection'>
Hello,
<span class='outer' id='spFirstName'>
<span data-bind='text: firstName'></span>
<span class='fill'></span>
</span>
<span class='outer' id='spLastName'>
<span data-bind='text: lastName'></span>
<span class='fill'></span>
</span>
!
<p>
<label for='cbUC'>Force Uppercase?</label>
<input type='checkbox' data-bind='checked: forceUppercase' id='cbUC' name='cbUC' />
</p>
</div>
<script scr="https://raw.githubusercontent.com/floyd-may/haymaker.js/master/haymaker-0.1.js"></script>
CSS
span.outer
{
position: relative;
display: inline-block;
}
span.fill
{
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
display: inline-block;
}
JavaScript
var model = new haymaker.object({
firstName: 'John',
lastName: 'Doe'
});
var view = new haymaker.object({
model: model,
forceUppercase: false,
firstName: function() {
if(this.forceUppercase()) {
return this.model.firstName().toUpperCase();
}
else {
return this.model.firstName();
}
}.haymakerprop(),
lastName: function() {
if(this.forceUppercase()) {
return this.model.lastName().toUpperCase();
}
else {
return this.model.lastName();
}
}.haymakerprop(),
init: function() {
ko.applyBindings(this.model, document.getElementById('inputSection'));
ko.applyBindings(this, document.getElementById('outputSection'));
},
highlightFirstName: function() {
$('#spFirstName .fill').stop(true, false).css({ backgroundColor: 'Green', opacity: 0.5 }).animate({ 'opacity': 0 });
},
highlightLastName: function() {
$('#spLastName .fill').stop(true, false).css({ backgroundColor: 'Green', opacity: 0.5 }).animate({'opacity': 0 });
}
});
var controller = new haymaker.object({
model: model,
view: view,
bindings: {
'model.firstName': function(newName) {
if(newName.length % 2 === 0) return;
this.view.highlightFirstName();
},
'model.lastName': function(newName) {
if(newName.length % 2 === 0) return;
this.view.highlightLastName();
}
}
});