The main relation: how to establish a connection and a model?

I have the following situation, and I think the best way to deal with it is to use the Backbone relation .
Please correct me if there is another solution.

I have one collection (1) and one model (2).
The result of the collection looks like (3), and the result of the model is like (4).

Finally, the view should look like this (5).

My questions:
1) can I use the Backbone relation to solve this situation?
2) If so, how do I rewrite the FeedsCollection to automatically retrieve the necessary data from the UserModel ?


(1)

 // FeedsCollection var FeedsCollection = Backbone.Collection.extend({ url: "http://localhost/feeds" }); 

(2)

 // User Model var UserModel = Backbone.Model.extend({ url: "http://localhost/user" }); 

(3) feedsCollection result

 //feedsCollection.toJSON(); [ {id:1, message: "something one", creator_id: 100}, {id:2, message: "something two", creator_id: 101}, ] 

(4) Result of userModel

 userModel = new UserModel({id: 100}); userModel.fetch(); userModel.toJSON(); // {id:100, name: "jhon"} userModel = new UserModel({id: 101}); userModel.fetch(); userModel.toJSON(); // {id:101, name: "herry"} 

(5) Finally, the result of the scan should look like this:

 [ {message: "something one", creator_id: 100, name: "jhon"}, {message: "something two", creator_id: 101, name: "herry"}, ] 
+4
source share
1 answer

You believed that you immediately returned the username from the server. To url "/ feeds" return:

 [ {message: "something one", creator_id: 100, name: "jhon"}, {message: "something two", creator_id: 101, name: "herry"}, ] 

If you just want the username to appear next to the message, this seems like a simple solution. I do not know what a server server is, but I am sure that this can be done efficiently.

So, answering your questions:

1) can I use the Backbone relation to handle this situation?

Perhaps you can use a plugin to solve this situation, but I do not recommend introducing a plugin to solve this specific example. It seems inefficient to request a server for custom models, just to display their name. However, in different situations this may be appropriate.

In any case, if you decide to load custom models with or without a plugin. You should ask some questions to find out if it is worth it:

  • How many requests will be generated? One for each user may be too much.
  • How many user models will the server return if you download everything in one request? All users can have a lot. Therefore, you only need to download the ones you need.
  • How much data will the server return? Do you really need all user attributes?

So in conclusion, I would still argue that you are returning the username directly from the server and downloading a specific user model only when you need more than the name.

0
source

Source: https://habr.com/ru/post/1414016/


All Articles