JSFiddle - React, Tailwind, and code Playground
by galenp
HTML
<script src="http://wiredwestwebdesign.com/jquery.tmpl.js"></script>
<script src="http://wiredwestwebdesign.com/knockout-1.1.2.js"></script>
<script src="http://wiredwestwebdesign.com/knockout.mapping.js"></script>
<script src="http://wiredwestwebdesign.com/json2.js"></script>
<form action="/echo" data-bind="submit: save">
<div id="editListing" data-bind="template: 'editListingTemplate'"></div>
<div id="saveListing" class="end-actions">
<button type="submit">Save Listings</button>
</div>
</form>
<script type="text/html" id="editListingTemplate">
<div class="warning message error" data-bind="visible: Response.HasWarning()">
<span>Correct the Following to Save</span>
<ul>
{{each(i, warning) Response.BusinessWarnings}}
<li data-bind="text: Message"></li>
{{/each}}
</ul>
</div>
<fieldset>
<div class="editor-label">
<label>Clicking submit should pickup the response JSON with a warning and display the error.<br />
Can change Name in textbox and tab off to confirm binding</label>
</div>
<div class="editor-field">
<input data-bind="value: Project_Name" class="title" />
</div>
Testing Databind of Project Name: <span data-bind="text: Project_Name" />
</fieldset>
</script>
CSS
.error {
background: none repeat scroll 0 0 #FBE3E4;
border-color: #FBC2C4;
color: #8A1F11;
}
.error, .alert, .notice, .success, .info {
border: 2px solid #DDDDDD;
margin-bottom: 1em;
padding: 0.8em;
}
JavaScript
var initialData = {
"Id": 440,
"Project_Name": "",
"Response": {
"HasWarning": false,
"BusinessWarnings": []
}
};
var viewModel = ko.mapping.fromJS(initialData);
viewModel.save = function() {
this.Response = null;
var data = ko.toJSON(this);
$.ajax({
url: '/echo/json/',
contentType: 'application/json',
type: "POST",
data: data,
dataType: 'json',
success: function(result)
{
var ajaxReply = {
"Id": 440,
"Project_Name": "project-name rebound",
"Response": {
"HasWarning": true,
"BusinessWarnings": [{
"ExceptionType": 0,
"Message": "test warning"}]
}
};
ko.mapping.updateFromJS(viewModel, ajaxReply );
alert('ViewModel has Warning: ' + viewModel.Response.HasWarning());
}
});
},
$(function() {
ko.applyBindings(viewModel);
});