Say you have a list of "vehicles" - you have an observableArray of these ko.observable()s.
You let your user add a new vehicle with the following:
var emptyVehicle = {
"make": "chevrolet",
"model": "corvette"
};
app.on('CLICKED_ADD_VEHICLE', function () {
var vehicle = new vehicleViewModel(emptyVehicle);
vehicle.hasWheels(true);
innerModel.sets.push(set);
});
If they save the vehicle, you get a real vehicle from your dataservice, and then replace the blank one with this:
app.on('CLICKED_SAVE', function (oldVehicle) {
var newVehicle = new vehicleViewModel(dataservice.createVehicle(oldVehicle));
innerModel.vehicles.remove(oldVehicle);
innerModel.vehicles.push(newVehicle);
});
I know I'm leaving some code out here, but this is more of a practices/approach question than a code question. Is this an acceptable approach to adding new items to a list? New up a temporary template, and throw it away in place of an actual item if the user saves?
I would not replace the vehicle, just:
Then when saving:
This will depend on how you want to handle the intermediate state of your UI; the state when the browser is waiting for a result from the server. You can generally group approaches to this into three schools of thought.
UI Blocking
One approach is to stop the user from making any more entries, display some wait indicator (spinning wheel), and call the server. When the server returns your data you then add it to the array/UI and remove the wait indicator. This approach ensures that your user is never queuing up actions while your server is down, since they can't perform actions while waiting for the server.
In this case, you wouldn't add the temporary data at all.
Queuing
This approach only blocks the item in question, putting an uneditable item into your UI and letting it become editable only after the server responds. In the meanwhile, the user can continue to perform actions. This approach is pretty friendly to the user, but can be tough to implement depending on how much editing is possible.
This is most similar to what you have implemented now. Add a temporary entity and replace it when you have the server data.
Eventual Consistency
With this approach, you just put in the data you expect to come back from the server and let the user continue on their way. When the server returns, you just update the missing data as Tomas Kirda shows in his answer. This approach is very friendly to the user but requires more care in dealing with server errors.
Overall, I like Tomas' answer, but you asked about best practices so I wanted to give you a broader picture.