Blacksad
Blacksad

Reputation: 15422

Backbone Relational and subviews, best "save" strategy

I'm using Backbone-relational like this:

class window.Car extends Backbone.RelationalModel

class window.Person extends Backbone.RelationalModel
    relations: [{
        type: Backbone.HasOne
        key: 'car'
        relatedModel: Car
    }]

There is also a PersonView, which embeds a subview CarView.

Now my question is, what is the best strategy when the user clicks "Save" in the PersonView? The problem is that the save will happen in two steps, first the car then the person. But what if validation fails with the person? It will cancel the save, but the car will be already saved!

Maybe Backbone-relational is not the best option here? Any alternative?

More generally, I'm more and more frustrated with Backbone playing not very nice with deeply embedded documents (I'm using MongoDB). Yes, the Todo app is nice, but the real world is more complex! Any guidance or tutorial would be very much appreciated.

Upvotes: 1

Views: 654

Answers (2)

Paul
Paul

Reputation: 2157

The best save strategy would be to save the whole thing atomically (in one step). Otherwise, you're always going to have these type of problems where failing to save one object on the server means you're going to have to destroy other objects on both the server and the client.

To support that, Backbone-relational has excellent support for serializing and deserializing nested objects.

Upvotes: 0

Robert
Robert

Reputation: 32755

It’s difficult to answer without to know the details, but, are you sure that you need relational models in the browser side?

Backbone is designed for restful applications. Is your API in the server side restful?

In your case (and without really understanding the constraints you have) I can think of the following implementation.

In the server the following URIs API:

[…]/carType/{carType}
[…]/persons/{person}
[…]/cars/{car}

In this implementation, “car” represents an actual physical object where “carType” represents a class of car. The backbone model for “car” contains the ID for the “carType” and the ID for the “person”. There are also backbone models for “carType” and “person”. In this way, when you want to associate a “person” and a “carType” you create a new “car” and make a POST to the server. As “car” is its own independent object (and has its own URL), you can operate in a transactional way with it (that is what, I think, you are asking).

I hope it helps and the answer its not very far of what you are actually trying to do.

Upvotes: 1

Related Questions