I had a similar issue recently and I improvised a bit.
If it would be to follow your example, I first retrieved all the customers and stored them into an observableArray()
, called customers
.
Afterwards, I wrote a function that takes as a parameter the customer object, and creates some other more proprieties dependant on the customer object. Because "my customer" had some foreign keys as attributes, I needed this behaviour to solve the foreign keys. I though the easiest way to accomplish it would be using ko.computed
. The coumputed could sove the foreign key based on the customer attributes.
My function looks something like this:
function ExtendedCustomer(customerValue) {
var self = {};
self.customer = customerValue;
self.department= ko.computed(function() {
read: function(){
return getString(self.customer.Department()).StringValue();
},
write: function(newValue){
var newString = createString(newValue);
self.customer.Department(newString.StringID());
}
});
self.description= ko.computed(function() {
read: function(){
return getString(self.customer.Description()).StringValue();
},
write: function(newValue){
var newString = createString(newValue);
self.customer.Description(newString.StringID());
}
});
...
return self;
}
This function would return an object that contains the customer + some other proprieties.
I called this function for all the customers retrieved and then store them into a different observableArray()
:
var helper = ko.observableArray()
for (var i = 0; i < customers().length; i++) {
helper.push(ExtendedCustomer(customers()[i]));
}
Then instead of binding to the original customer I was binding to the extended ones.
The computed offered me the functionality to create some more proprieties based on the customer entity and then modify the customer entity if one of this added proprieties has been changed.(Read how can you use a computed to read and write values.)
I chose to do this because I only needed these extended objects in one of mine viewmodels. If you need them in more than one viewmodels you could scope this extended objects in an upper level so it would be common to your viewmodels.
If you need to scope it to more than one viewmodel you could also follow the example in John Papa's course and add proprieties to the customer entity by mapping the DTO's to entities. This way it would be easier for you if you want to access it in different vm's. The only down would be if you need to add a lot of properties(or solve foreign keys) you would have a lot of functionality on the dataservice if you follow John Papa's example. You should move it into a mediator object.