I'm binding data to a page using KnockoutJS, the ViewModel is being populated by an JSON response from an AJAX call using the mapping plugin, like this:
$(function () {
$.getJSON("@Url.Action("Get")",
function(allData) {
viewModel = ko.mapping.fromJS(allData);
viewModel.Brokers.Url = ko.computed(function()
{
return 'BASEURLHERE/' + this.BrokerNum();
});
ko.applyBindings(viewModel);
});
});
The middle part there doesn't work (it works fine without that computed property). "Brokers" is an observable array, and I want to add a computed value to every element in the array called URL. I'm binding that Brokers array to a foreach, and I'd like to use that URL as the href
attribute of an anchor. Any ideas?
I've been working through very similar issues and I've found that you can intercept the creation of the Broker objects and insert your own fields using the mapping options parameter:
var data = { "Brokers":[{"BrokerNum": "2"},{"BrokerNum": "10"}] };
var mappingOptions = {
'Brokers': {
create: function(options) {
return (new (function() {
this.Url = ko.computed(function() {
return 'http://BASEURLHERE/' + this.BrokerNum();
}, this);
ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
})());
}
}
};
viewModel = ko.mapping.fromJS(data, mappingOptions);
ko.applyBindings(viewModel);
Here is a fiddle to demonstrate this: http://jsfiddle.net/pwiles/ZP2pg/