Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 0 down vote accepted

It's acceptable, but it's not really preferred. What happens if someone changes the code latter on, and it fails to send oldVehicle? What happens if the CLICKED_SAVE event is triggered again? What happens if the AJAZ call itself just fails?

Better practice is to design your app to begin with an empty innerModel.vehicles array, and then have addVehicle be a method of app that spools up a new vechicleViewModel and pushes it to the array.

Generally, events should call methods, even if they aren't UI events, unless you have a good reason not to.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.