How to generate model id's with Backbone.js

前端 未结 3 550
梦谈多话
梦谈多话 2021-01-30 23:22

I am setting up the backbone sync mechanism and am a bit confused where to generate the id\'s for the models.

When I create a new model, should backbone be generating an

3条回答
  •  再見小時候
    2021-01-31 00:12

    I'm providing a second answer to simplify the code you need to study to get the main points you're pondering about - the actual round about from model to server and how ids play their role.

    Say you define a model - Let's go with Jurassic Park.

    // Define your model
    var Dinosaur = Backbone.Model.extend({
        defaults: {
            cavemanEater: undefined    // Has one property, nom nom or not.
        },
        urlRoot: 'dino'               // This urlRoot is where model can be saved or retrieved
    });
    
    var tRex = new Dinosaur({'cavemanEater':true});
    

    You now have instantiated a dinosaur that is a meat eater. Roar.

    console.log(tRex);
    

    What you should notice is that in the properties of tRex, your model does not have an id. Instead, you will see a cID which you can think of as a temporary id that Backbone automatically assigns to your models. When a model doesn't have an id it is considered new. The concept of persisting a model (either to a database or local storage) is what allows you to go back to that resource after you've created it and do things like save (PUT) or destroy (DELETE). It would be hard to find that resource if you had no way to point directly at it again! In order to find that resource, your model needs an id, something it currently does not have.

    So as the above answers have explained it is the job of your database (or localstorage, or some other solution) to provide Backbone with a resource id. Most of the time, this comes from the resource id itself, aka - the primary key id of your model in some table.

    With my setup, I use PHP and mySQL. I would have a table called Dinosaur and each row would be a persistent representation of my dino model. So I'd have an id column (unique auto-incrementing int), and cavemanEater (bool).

    The data communication flow happens like this.

    1. You create a model.
    2. The model is new so it only has a cID - no proper ID.
    3. You save the model.
    4. The json representation of your model is SENT to your server (POST)
    5. Your server saves it to the table and gives it a resource id.
    6. Your server SENDS BACK a json representation of the data {id:uniqueID}
    7. Backbone RECEIVES this json representation with id
    8. Backbone automagically updates your model with an id.

    Here is what annotated code looks like.

    CLIENT:

    tRex.save();
    // {'cavemanEater':true} is sent to my server
    // It uses the urlRoot 'dino' as the URL to send. e.g. http://www.example.com/dino
    

    SERVER:

    // Is setup to accept POST requests on this specific ROUTE '/dino'
    // Server parses the json into something it can work with, e.g. an associative array
    // Server saves the data to the database. Our data has a new primary id of 1.
    // Data is now persisted, and we use this state to get the new id of this dino.
    
    $dinoArray = array('id'=>1, 'cavemanEater'=>true);
    $dinoJSON = json_encode($dinoArray);
    
    // Server does something to send $dinoJSON back.
    

    CLIENT:

    // If successful, receives this json with id and updates your model.
    

    Now your tRex has an id = 1. Or should I say...

    tRex.toJSON();
    // RETURNS {'id':'1', 'cavemanEater':'true'}
    

    Congrats. If you do this tRex.isNew() it will return false.

    Backbone is smart. It knows to POST new models and PUT models that already have a resource id.

    The next time you do this:

    tRex.save();
    

    Backbone will make a PUT request to the following URL.

    http://www.example.com/dino/1

    That is the default behavior by the way. But what you'll notice is that the URL is different than save. On the server you would need a route that accepts /dino/:id as opposed to /dino

    It will use the /urlRoot/:id route pattern for your models by default unless you tweak it otherwise.

    Unfortunately, dinosaurs are extinct.

    tRex.destroy();
    

    This will call... Can you guess? Yep. DELETE request to /dino/1.

    Your server must distinguish between different requests to different routes in order for Backbone to work. There are several server side technologies that can do this.

    Someone mentioned Sinatra if you're using Ruby. Like I said, I use PHP and I use SLIM PHP Framework. It is inspired by Sinatra so it's similar and I love it. The author writes some clean code. How these RESTful server implementations work is outside the scope of this discussion though.

    I think this is the basic full travel of new Backbone data with no id, across the internets to your server where it generates, and sends back the resource id, to make your model live happily ever after. (Or destroy() not...)

    I don't know if this is too beginner for you but hopefully it will help someone else who runs into this problem. Backbone is really fun to program with.

    Other similar Answers: Ways to save Backbone JS model data

提交回复
热议问题