简体   繁体   English

如何使用BackboneJS获取/ users / profile和/ users / friends

[英]How to fetch on /users/profile and /users/friends with BackboneJS

I have an API with many urls like: 我有很多网址的API,例如:

/users/profile -> GET the currently connected user 
 /users/bestfriend -> GET the currently connected users' best friend (most bestfriend of bestfriends)
 /users/wife -> GET the currently connected users' wife


 /users/friends -> GET the currently connected users' friends
 /users/bestfriends -> GET the currently connected users' best friends
 /users/childrens -> GET the currently connected users' childrens
 /users/neighbours -> GET the currently connected users' neighbours

I'm new to Backbone and i don't really know if the currently connected user should be fetched as a collection or a simple model for exemple. 我是Backbone的新手,我真的不知道是否应该将当前连接的用户作为集合或简单模型来获取。

I know the current user could be boostrapped like the Backbone doc mention but it's not the point here, just assume i can't boostrap the current user model. 我知道当前用户可能会像Backbone doc提到的那样受到提振,但这不是重点,只是假设我无法提升当前用户模型。


So how can i redirect my fetches to the API URLs? 那么,如何将提取的内容重定向到API URL? Should i provide each time an option like {"operation":"profile"} or {"operation":"friends"} , or modify the collection url before doing the fetch? 我应该每次提供诸如{"operation":"profile"}{"operation":"friends"} ,还是在执行提取之前修改集合网址?

Thanks 谢谢

Use the model.urlRoot property to specify the URL of the model if you wish to use the model 'outside' of a collection. 如果要使用集合的“外部”模型,请使用model.urlRoot属性指定模型的URL。 It'll automatically append an id to the end of the URL if it's a new model (ie id==null ) and send a POST on creation. 如果是新模型,它将自动在URL末尾附加一个id(即id==null ),并在创建时发送POST。 Else it'll fetch (GET) at the specified url. 否则,它将在指定的网址获取(GET)。

If you don't want to have an id appended at the end: Just overwrite model.url to generate the actual endpoint URL that you want to fetch/put/post to. 如果不想在末尾附加ID:只需覆盖model.url即可生成要获取/放入/发布到的实际端点URL。

Collections also have a property called url - if the url or urlRoot of the model isn't specified the collection's url is picked up as the root (if that model is part of that collection). 集合还具有一个称为url的属性-如果未指定模型的url或urlRoot,则将集合的url作为根(如果该模型是该集合的一部分)。

So you could just do either of these: 因此,您可以执行以下任一操作:

model.urlRoot = '/users/profile'; //appends id on put/delete requests
model.url = '/users/profile'; //direct endpoint. Can also be a function
collection.url = '/users/friends'; //fetch endpoint for collection. Could also be used by models to put to with appended id.

The Backbone's doc is quite comprehensive and self explanatory. 骨干网的文档非常全面,可以自我解释。 I suggest you read these parts for example Model.urlRoot 我建议您阅读这些部分,例如Model.urlRoot

UPDATE : As per your new URLs 更新 :根据您的新URL

I think the confusion is because of the way URLs are designed. 我认为造成混淆的原因是URL的设计方式。 It's not good practice to have end-points as plural/singular: 端点为复数/单数不是一个好习惯:

Ex: /user/friends - fine get all friends of user. 例如: /user/friends很好地获得user的所有朋友。 But which user? 但是哪个用户呢? Better still: /users/{id}/friends - get friends of a specific user. 更妙的是: /users/{id}/friends获取特定用户的朋友。

GET specific friend for user: /users/{id}/friends/{id} 为用户获取特定的朋友: /users/{id}/friends/{id}

I suggest adding ids to your URLs to make the most of backbone's built in REST-able functionality. 我建议在您的URL中添加ID,以充分利用骨干网内置的REST功能。 Else, just define your own properties and logic and have separate function like 'save' to fire $.ajax calls yourself and do something on success/error callbacks. 否则,只需定义您自己的属性和逻辑并具有单独的功能(如“保存”)即可触发$.ajax调用您自己并在成功/错误回调上执行某些操作。

Whether they are models or collections will totally be up to you. 无论是模型还是收藏,完全取决于您。 Fortunately/unfortunately there is more than one way to do it in Backbone. 幸运的是,在Backbone中有多种方法可以做到这一点。 If you follow BB's way it'll offer a cleaner way of doing things since the framework expects and follows certain conventions. 如果您遵循BB的方法,它将提供一种更简洁的处理方式,因为该框架期望并遵循某些约定。 If not, you can always custom create. 如果没有,您可以随时自定义创建。 I've done both ways. 我做过两种方式。 Custom creating seems easier, following convention takes some planning but keeps it much cleaner albeit hides/abstracts away stuff from the programmer 'under the hood' whereas explicit ajax calls make it explicit. 自定义创建似乎更容易,遵循约定需要一些计划,但是可以使其更加整洁,尽管“隐藏”隐藏/抽象了程序员的内容,而显式ajax调用使其变得显式。

It's a tradeoff. 这是一个权衡。 I suggest restructure your endpoints and use the url properties accordingly. 我建议您重组端点并相应地使用url属性。 Else just do what makes sense to you and your team and stick with it. 否则,请尽一切可能对您和您的团队有意义,并坚持下去。

You have to create several Models and Collections any of them related to one of your URLS. 您必须创建几个与您的一个URLS相关的模型和集合。

var Profile = Backbone.Model.extend({
  url: "/users/profile"
});

var BestFriend = Backbone.Model.extend({
  url: "/users/bestfriend"
});

// ...

var Friend = Backbone.Model.extend({});

var Friends = Backbone.Collection.extend({
  model: Friend,
  url: "/users/friends"
});

You also can use Friend as the parent class of BestFriend : 您还可以将Friend用作BestFriend的父类:

var BestFriend = Friend.extend({
  url: "/users/bestfriend"
});

Or even create a Person class as parent for every person : 甚至创建一个Person类作为每个人的父母:

var Person = Backbone.Model.extend({});

var Friends = Backbone.Collection.extend({
  model: Person,
  url: "/users/friends"
});

var Profile = Person.extend({
  url: "/users/profile"
});

var BestFriend = Person.extend({
  url: "/users/bestfriend"
});

As you have separate URLS to retrieve the data of everyone of the elements you should make several fetches: 由于您有单独的URL来检索每个元素的数据,因此应进行几次访存:

var profile = new Profile();
var bestFriend = new BestFriend();
var friends = new Friends();

profile.fetch();
bestfriend.fetch();
friends.fetch();

You can reference all the elements into your Profile instance with things like this: 您可以使用以下内容将所有元素引用到您的Profile实例中:

var Profile = Person.extend({
  url: "/users/profile",
  initialize: function( opts ){
    this.bestFriend = opt.bestfriend;
    // ...
  }
});

var bestFriend = new BestFriend();
var friends = new Friends();

var profile = new Profile({
  bestfriend: bestfriend
});

There are several approaches to organize the elements, also to listen to events on them, but all this is just a matter of taste, and which architecture you fill more comfortable with. 有几种方法可以组织元素,也可以听取有关事件的信息,但这只是品味的问题,您更喜欢哪种架构。

Essentially I agree with the first answer, but to keep it simple, you could start to use ids for the users and fetch them individually. 从本质上讲,我同意第一个答案,但为简单起见,您可以开始为用户使用id并分别获取它们。 This might create a bit of extra load, but it should keep the code cleaner until you need to optimize. 这可能会产生一些额外的负载,但是在您需要进行优化之前,它应该使代码更整洁。

You might run into problems with the current API design. 当前的API设计可能会遇到问题。 What if in the future you want the best friend of the wife? 如果将来您想要妻子的最好的朋友怎么办? You will have an object which has the url "/user/wife" and you would then say "/user/wife/bestfriend". 您将拥有一个URL为“ / user / wife”的对象,然后说“ / user / wife / bestfriend”。 Next someone wants to expand this and have "/user/wife/bestfriend/children/". 接下来,某人想要扩展它并使用“ /用户/妻子/最好的朋友/孩子/”。 This would be rather complex to parse on the backend. 在后端解析非常复杂。

Essentially, instead of making separate calls for wives and children, have the profile call return the ids of the associated users: 本质上,让配置文件调用返回关联用户的ID而不是分别呼叫妻子和孩子:

/profile
{
  id: 165735,
  name: "Peter",
  age: 45,
  wifeId: 246247,
  childrenIds: [352356, 134098]
}

Then fetching the wife would simply be: 然后拿到妻子将是:

/users/246247

This would make the wife stay a real User and not just someone's wife. 这将使妻子成为真正的用户,而不仅仅是某人的妻子。 You can check the security here when retrieving a user, since you anyway have the relationships stored in the database. 检索用户时,您可以在此处检查安全性,因为无论如何您都已将关系存储在数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从使用 fetch api 和 javascript 获取的用户列表中的模型中显示用户配置文件 - How to show a user profile in a model from the list of users fetched using fetch api with javascript Backbonejs应用程序导航到#users时会自动加载页面`state =#users` - Backbonejs app automatically loads page `?state=#users` when navigating to `#users` “只能将请求发送给此应用程序的朋友或用户” - “Can only send requests to friends or users of this application” 用户和朋友使用Firebase(AngularFire)的设计和实现 - Users & Friends Design and Implementation with Firebase (AngularFire) 吸引大量Facebook用户-发布到朋友墙 - Taking a Facebook array of users - post to friends wall Backbonejs-如何打印获取的结果? - Backbonejs - How can I print the results of a fetch? 发布用户数据,用于个人资料页面 - Publishing users data, for profile page PHP:如何允许用户更改其个人资料的背景颜色? - PHP: How to allow users to change background color of their profile? 从多个用户列表中选择他/她后,如何导航到特定用户的个人资料页面? - How to navigate to a specific users profile page after selecting him/her from a list of multiple users? 如何使用jquery从sharepoint用户配置文件db获取用户 - how to get users from sharepoint user profile db using jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM