JSFiddle - React, Tailwind, and code Playground
by Mark
HTML
<script src="http://documentcloud.github.io/underscore/underscore.js"></script>
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.js"></script>
<div id="defAccount">
<p>
Account Option :
<select data-bind="options: accounts,
optionsText: 'paymentOption',
value: selectedAccount,
optionsCaption: 'Choose...'"></select>
<div class="form-horizontal">
<div data-bind="if: selectedAccount() ">
<label data-bind="text: selectedAccount().Id"></label>
<label data-bind="text: selectedAccount().deferredAccountId"></label>
<label data-bind="text: selectedAccount().paymentOptionId"></label>
<div data-bind="visible: accounts().length < 1">
<label>There are currently no records to show - sucka.</label>
</div>
</div>
</div>
</p>
</div>
JavaScript
// Model
function deferredAccount(data) {
var self = this;
self.paymentOption = ko.observable(data.PaymentOption);
self.timeOption = ko.observable(data.TimeOption);
self.Id = ko.observable(data.Id);
self.deferredAccountId = ko.observable(data.DeferredAccountId);
self.paymentOptionId = ko.observable(data.PaymentOptionId);
self.timeOptionId = ko.observable(data.TimeOptionId);
self.year = ko.observable(data.Year);
}
//ViewModel
function accountViewModel(){
var self = this;
self.accounts = ko.observable();
self.selectedAccount = ko.observable();
$.ajax("/echo/json/", {
data: {
json: ko.toJSON(account)
},
type: "POST",
dataType: 'json',
success: function(data) {
//2 objects here
console.log(ko.toJSON(data));
var mAccounts = _.map(data, function(item) {
return new deferredAccount(item);
});
self.accounts(mAccounts);
}
});
}
// The point of this is to show that if the JsonResponse from the Server is NOT an array/list (IList<T>, ICollection<T>, IEnumerable<T>, etc), then the response will NOT work with the _map() high order function because it expects an array. Below are 2 examples of a JsonResponse, one returned from an ICollection<T> and one returned as a regular View Model.
// Toggle the commented var account to view the results .... Mark 7/10/2015
//Works
var account = [{"PaymentOption":"10 ANNUAL INSTALL","TimeOption":"SPECIFIC //DATE","Id":2,"DeferredAccountId":1,"PaymentOptionId":"10AN","TimeOptionId":"DATE","Year":0}];
//Doesn't work
//var account = {"PaymentOption":"10 ANNUAL INSTALL","TimeOption":"SPECIFIC DATE","Id":2,"DeferredAccountId":1,"PaymentOptionId":"10AN","TimeOptionId":"DATE","Year":0};
ko.applyBindings(new accountViewModel(),...