How to create model id using Backbone.js

I set up the synchronization mechanism of the main database and got a little confused where to generate the identifier for the models.

When I create a new model, do I need to create a basic framework and set an identifier, or should I implement an identifier generation method, or is there some mechanism in which I "PUT" the data to the server that generates an id and returns a model with an identifier?

+21
May 28 '12 at 21:34
source share
3 answers

or is there some kind of mechanism in which I "PUT" the data to a server that generates an identifier and returns a model with an identifier?

View. When you invoke the save method of your model, the spine does POST XHR, and your application server must respond with JSON containing the identifier. Here you can see an example: http://addyosmani.com/blog/building-backbone-js-apps-with-ruby-sinatra-mongodb-and-haml/

Quote from the link:

post '/api/:thing' do # parse the post body of the content being posted, convert to a string, insert into # the collection #thing and return the ObjectId as a string for reference oid = DB.collection(params[:thing]).insert(JSON.parse(request.body.read.tos)) "{\"id\": \"#{oid.to_s}\"}" end 

If you do not know that Ruby takes into account the fact that the last expression that is evaluated is automatically returned by the method.

+9
May 29 '12 at 1:27
source share

I am providing a second answer to simplify the code that you need to learn to get the main points that you are thinking about - the actual round from model to server and how identifiers play their part.

Suppose you have defined a model - release 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}); 

Now you have created a copy of the dinosaur, which is food. The roar.

 console.log(tRex); 

What you should notice is that in the tRex properties your model does not have an identifier. Instead, you will see the cID, which can be considered a temporary identifier that Backbone automatically assigns to your models. When a model does not have an identifier, it is considered new. The concept of saving the model (either in the database or in local storage) allows you to return to this resource after you created it and do something like save (PUT) or destroy (DELETE). It would be difficult to find this resource if you had no way to point directly to it! To find this resource, your model needs an identifier, something is currently missing.

Since the above answers explained that this is the work of your database (or localstorage or some other solution), to provide a Backbone resource identifier. In most cases, this comes from the resource identifier itself, aka the identifier of the primary key of your model in some table.

With my installation, I use PHP and mySQL. I will have a table called "Dinosaur", and each row will be a constant representation of my dinosaur model. This way I will have an id column (unique auto-incrementing int) and cavemanEater (bool).

The flow of data is as follows.

  • You are creating a model.
  • The model is new, so it only has the identifier cID - there is no proper identifier.
  • You save the model.
  • json representation of your model sent to your server (POST)
  • Your server stores it in a table and assigns it a resource identifier.
  • SENDS BACK server presents a json representation of data {id: uniqueID}
  • The backbone will GET this json view with id
  • Backbone automatically updates your model with an identifier.

Here's what the annotated code looks like.

CLIENT:

 tRex.save(); // {'cavemanEater':true} is sent to my server // It uses the urlRoot 'dino' as the URL to send. eg 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, eg 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 id = 1. Or should I say ...

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

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

The highway is smart. He knows POST new models and PUT models that already have a resource identifier.

Next time you will do the following:

 tRex.save(); 

The trunk will make a PUT request to the following URL.

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

This is the default behavior. But you will notice that the URL is different than saving. On the server, you need a route that accepts / dino /: id as opposed to / dino

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

Unfortunately, the dinosaurs became extinct.

 tRex.destroy(); 

It will cause ... Can you guess? Yeah. DELETE query / dino / 1.

For Backbone to work, your server must distinguish between different requests for different routes. There are several server-side technologies that can do this.

Someone mentioned Sinatra if you are using Ruby. As I said, I use PHP and I use SLIM PHP Framework. He is inspired by Sinatra, so he is like, and I like it. The author writes clean code. How these RESTful server implementations work is beyond the scope of the discussion.

I think this is the basic complete transfer of new Backbone data without id, via the Internet to your server, where it generates, and sends back the resource identifier so that your model lives happily. (Or destroy() not ...)

I don’t know if this is too new for you, but hopefully this will help someone else who is facing this problem. The highway is very interesting for programming.

Other Similar Answers: Ways to Save JB Base Model Data

+56
May 29 '12 at 5:46 a.m.
source share

What I understand from your question is that you want to have a collection with models that exist on the server. To assemble these collections into a collection, you need to add the collection call 'fetch ()' to the collection.

The url would be "/ users" or something similar, which would have to return an array of objects with user data. Then each element of the array will be passed to UserCollection.add (). Well, actually it will be transmitted right away, but you understand.

After that, your collection will be filled. The model URL is for updating and saving a single model. The collection URL will also be used to create models. Basic RESTful synchronization, like Ruby on Rails. You can learn more about this in the Ruby on Rails documentation:

http://guides.rubyonrails.org/routing.html

What you usually do is have a different url for your model than for your controller. After filling out your collection, you have an identifier for each model because they came from the server.

Now, when you add a new model based on user input, you do something like this:

 var HomeModel = Backbone.Model.extend({ defaults: { lead: "not logged in", }, url: 'test.php', initialize: function(){ _.bindAll(this, 'handleSave', 'handleError'); // Save already knows if this.isNew. this.save(undefined, {success: this.handleSave, error: this.handleError}); }, handleSave: function(model, response){ this.model.reset(model); }, handleError: function(){ }, }); var HomeView = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'render'); this.model = new HomeModel(); this.model.bind("change", this.render); }, el: 'div', render: function() { // Do things to render... } }); var homeView = new HomeView(); 

An example from another question that I answered, I just add the appropriate things.

The general idea is to save the model when it is created, if you need it somewhere else, you can simply move the code to the model function and call it based on events or something else.

+4
May 29 '12 at 12:04 a.m.
source share



All Articles