Utility functions in KnockoutJS
http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html
by db_dev
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
<select id="ddlCountryName" data-bind="options: CountryList,
optionsText: 'CountryName',
optionsValue: 'CountryId',
optionsCaption: '-- Select --',
value: $root.CountryId"></select>
JavaScript
var serverList = [{
"CountryId": 4,
"CountryName": "United States"
}, {
"CountryId": 5,
"CountryName": "Germany"
}, {
"CountryId": 6,
"CountryName": "Spain"
}, {
"CountryId": 7,
"CountryName": "England"
}, {
"CountryId": 8,
"CountryName": "China"
}, {
"CountryId": 9,
"CountryName": "South America"
}, {
"CountryId": 10,
"CountryName": "Canada"
}, {
"CountryId": 11,
"CountryName": "Japan"
}];
var viewModel = function() {
var self = this;
self.CountryList = ko.observableArray(serverList);
self.regionNametext = ko.computed(function() {
var CountryNametext
ko.utils.arrayForEach(serverList, function(item) {
if (self.CountryId == item.CountryId) {
CountryNametext = item.CountryName;
}
});
return CountryNametext;
}, self)
};
var bfViewModel = new viewModel();
ko.applyBindings(bfViewModel);