保存 Backbone.js 模型数据的方法? [英] Ways to save Backbone.js model data?

查看:18
本文介绍了保存 Backbone.js 模型数据的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更喜欢前端开发,最近开始在我的应用程序中探索 Backbone.js.我想将模型数据持久化到服务器.

I am more into front end development and have recently started exploring Backbone.js into my app. I want to persist the model data to the server.

能否请您解释一下保存模型数据的各种方法(使用 json 格式).我在服务器端使用 Java.此外,我主要看到 REST 用于保存数据.因为我更喜欢前端开发,所以我不知道 REST 和其他类似的东西.

Could you please explain me the various way to save the Model data (using json format). I am using Java on server side. Also I have mainly seen REST being used to save data. As i am more into front end dev, i am not aware of REST and other similar stuff.

如果有人能用一些简单的例子向我解释这个过程,那就太好了.

It would be great if someone could please explain me the process with some simple example.

推荐答案

基本上模型有一个称为属性的属性,它是某个模型可能具有的各种值.Backbone 使用 JSON 对象作为一种简单的方法来使用采用 JSON 对象的各种方法来填充这些值.示例:

Basically Models have a property called attributes which are the various values a certain model may have. Backbone uses JSON objects as a simple way to populate these values using various methods that take JSON objects. Example:

Donuts = Backbone.Model.extend({
    defaults: {
        flavor: 'Boston Cream',  // Some string
        price: '0.50'  // Dollars
    }
});

要填充模型,有几种方法可以这样做.例如,您可以通过传入一个名为 set() 的 JSON 或 use 方法来设置模型实例,该方法接受一个 JSON 属性对象.

To populate the model there are a few ways to do so. For example, you can set up your model instance by passing in a JSON OR use method called set() which takes a JSON object of attributes.

myDonut = new Donut({'flavor':'lemon', 'price':'0.75'});
mySecondHelping = new Donut();
mySecondHelping.set({'flavor':'plain', 'price':'0.25'});

console.log(myDonut.toJSON());
// {'flavor':'lemon', 'price':'0.75'}
console.log(mySecondHelping.toJSON());
// {'flavor':'plain', 'price':'0.25'}

这让我们开始保存模型并将它们持久化到服务器.有大量关于什么是 REST/RESTful?"的详细信息.在这里用简短的介绍来解释这一切有点困难.特别是在 REST 和 Backbone 保存方面,您需要关注的是 HTTP 请求的语义以及您对数据的处理方式.

So this brings us up to saving models and persisting them either to a server. There is a whole slew of details regarding "What is REST/RESTful?" And it is kind of difficult to explain all this in a short blurb here. Specifically with regard to REST and Backbone saving, the thing to wrap your head around is the semantics of HTTP requests and what you are doing with your data.

您可能习惯了两种 HTTP 请求.获取和发布.在 RESTful 环境中,这些动词对于 Backbone 假定的特定用途具有特殊含义.当您想从服务器获取某个资源(例如我上次保存的甜甜圈模型、博客条目、计算机规范)并且该资源存在时,您可以执行 GET 请求.相反,当您要创建新资源时,您可以使用 POST.

You're probably used to two kinds of HTTP requests. GET and POST. In a RESTful environment, these verbs have special meaning for specific uses that Backbone assumes. When you want to get a certain resource from the server, (e.g. donut model I saved last time, a blog entry, an computer specification) and that resource exists, you do a GET request. Conversely, when you want to create a new resource you use POST.

在进入 Backbone 之前,我什至从未接触过以下两种 HTTP 请求方法.放置和删除.这两个动词对 Backbone 也有特定的含义.当您想要更新资源时(例如,将柠檬甜甜圈的风味更改为柠檬甜甜圈等),您可以使用 PUT 请求.当您想从服务器上一起删除该模型时,您可以使用 DELETE 请求.

Before I got into Backbone, I've never even touched the following two HTTP request methods. PUT and DELETE. These two verbs also have specific meaning to Backbone. When you want to update a resource, (e.g. Change the flavor of lemon donut to limon donut, etc.) you use a PUT request. When you want to delete that model from the server all together, you use a DELETE request.

这些基础知识非常重要,因为对于您的 RESTful 应用程序,您可能会有一个 URI 名称,该名称将根据您使用的请求动词类型执行适当的任务.例如:

These basics are very important because with your RESTful app, you probably will have a URI designation that will do the appropriate task based on the kind of request verb you use. For example:

// The URI pattern
http://localhost:8888/donut/:id

// My URI call
http://localhost:8888/donut/17

如果我对该 URI 进行 GET,它将获得 ID 为 17 的甜甜圈模型. :id 取决于您如何在服务器端保存它.这可能只是数据库表中甜甜圈资源的 ID.

If I make a GET to that URI, it would get donut model with an ID of 17. The :id depends on how you are saving it server side. This could just be the ID of your donut resource in your database table.

如果我用新数据向那个 URI 做一个 PUT,我会更新它,保存它.如果我 DELETE 到那个 URI,那么它会从我的系统中清除它.

If I make a PUT to that URI with new data, I'd be updating it, saving over it. And if I DELETE to that URI, then it would purge it from my system.

使用 POST,由于您尚未创建资源,因此它不会具有已建立的资源 ID.也许我想创建资源的 URI 目标就是这样:

With POST, since you haven't created a resource yet it won't have an established resource ID. Maybe the URI target I want to create resources is simply this:

http://localhost:8888/donut

URI 中没有 ID 片段.所有这些 URI 设计都取决于您以及您对资源的看法.但是关于 RESTful 设计,我的理解是您希望将您的 HTTP 请求的动作动词和资源保留为名词,使 URI 易于阅读和人性化.

No ID fragment in the URI. All of these URI designs are up to you and how you think about your resources. But with regard to RESTful design, my understanding is that you want to keep the verbs of your actions to your HTTP request and the resources as nouns which make URIs easy to read and human friendly.

你还在我身边吗?:-)

Are you still with me? :-)

那么让我们重新考虑一下 Backbone.Backbone 很棒,因为它为您做了很多工作.为了保存我们的甜甜圈和 secondHelping,我们只需这样做:

So let's get back to thinking about Backbone. Backbone is wonderful because it does a lot of work for you. To save our donut and secondHelping, we simply do this:

myDonut.save();
mySecondHelping.save();

Backbone 很聪明.如果您刚刚创建了一个甜甜圈资源,它将没有来自服务器的 ID.它有一个叫做 cID 的东西,这是 Backbone 在内部使用的东西,但由于它没有官方 ID,它知道它应该创建一个新资源并发送一个 POST 请求.如果您从服务器获取模型,如果一切正常,它可能会有一个 ID.在这种情况下,当你 save() Backbone 假设你想要更新服务器并且它会发送一个 PUT.要获取特定资源,您可以使用 Backbone 方法 .fetch() 并发送 GET 请求.当您在模型上调用 .destroy() 时,它会发送 DELETE.

Backbone is smart. If you just created a donut resource, it won't have an ID from the server. It has something called a cID which is what Backbone uses internally but since it doesn't have an official ID it knows that it should create a new resource and it sends a POST request. If you got your model from the server, it will probably have an ID if all was right. In this case, when you save() Backbone assumes you want to update the server and it will send a PUT. To get a specific resource, you'd use the Backbone method .fetch() and it sends a GET request. When you call .destroy() on a model it will send the DELETE.

在前面的示例中,我从未明确告诉 Backbone URI 在哪里.让我们在下一个示例中这样做.

In the previous examples, I never explicitly told Backbone where the URI is. Let's do that in the next example.

thirdHelping = Backbone.Model.extend({
    url: 'donut'
});
thirdHelping.set({id:15});  // Set the id attribute of model to 15
thirdHelping.fetch();  // Backbone assumes this model exists on server as ID 15

Backbone 将在 http://localhost:8888/donut/15 获得第三个帮助,它会简单地将/donut 词干添加到您的站点根目录.

Backbone will GET the thirdHelping at http://localhost:8888/donut/15 It will simply add /donut stem to your site root.

如果你还和我在一起,很好.我认为.除非你糊涂了.但无论如何我们都会跋涉.第二部分是服务器端.我们已经讨论了 HTTP 的不同动词以及这些动词背后的语义含义.您、Backbone 和您的服务器必须共享的含义.

If you're STILL with me, good. I think. Unless you're confused. But we'll trudge on anyway. The second part of this is the SERVER side. We've talked about different verbs of HTTP and the semantic meanings behind those verbs. Meanings that you, Backbone, AND your server must share.

您的服务器需要了解 GET、POST、PUT 和 DELETE 请求之间的区别.正如您在上面的示例中看到的,GET、PUT 和 DELETE 都可以指向相同的 URI http://localhost:8888/donut/07 除非您的服务器可以区分这些 HTTP 请求,否则它对如何处理该资源感到非常困惑.

Your server needs to understand the difference between a GET, POST, PUT, and DELETE request. As you saw in the examples above, GET, PUT, and DELETE could all point to the same URI http://localhost:8888/donut/07 Unless your server can differentiate between these HTTP requests, it will be very confused as to what to do with that resource.

这是您开始考虑 RESTful 服务器端代码的时候.有些人喜欢Ruby,有些人喜欢.net,我喜欢PHP.我特别喜欢 SLIM PHP 微框架.SLIM PHP 是一个微框架,它有一个非常优雅和简单的工具集来处理 RESTful 活动.您可以像上面的示例一样定义路由 (URI),并且根据调用是 GET、POST、PUT 还是 DELETE,它将执行正确的代码.还有其他类似于 SLIM 的解决方案,如 Recess、Tonic.我相信像 Cake 和 CodeIgniter 这样更大的框架也做类​​似的事情,尽管我喜欢最小的.我说我喜欢 Slim 吗?;-)

This is when you start thinking about your RESTful server end code. Some people like Ruby, some people like .net, I like PHP. Particularly I like SLIM PHP micro-framework. SLIM PHP is a micro-framework that has a very elegant and simple tool set for dealing with RESTful activities. You can define routes (URIs) like in the examples above and depending on whether the call is GET, POST, PUT, or DELETE it will execute the right code. There are other solutions similar to SLIM like Recess, Tonic. I believe bigger frameworks like Cake and CodeIgniter also do similar things although I like minimal. Did I say I like Slim? ;-)

这是服务器上的摘录代码的样子(即特别是关于路由的.)

This is what excerpt code on the server might look (i.e. specifically regarding the routes.)

$app->get('/donut/:id', function($id) use ($app) {
    // get donut model with id of $id from database.
    $donut = ...
    
    // Looks something like this maybe:
    // $donut = array('id'=>7, 'flavor'=>'chocolate', 'price'=>'1.00')

    $response = $app->response();
    $response['Content-Type'] = 'application/json';
    $response->body(json_encode($donut));
});

这里需要注意的是,Backbone 需要一个 JSON 对象.如果可以,请始终让您的服务器将内容类型指定为application/json"并以 json 格式对其进行编码.然后当 Backbone 收到 JSON 对象时,它知道如何填充请求它的模型.

Here it's important to note that Backbone expects a JSON object. Always have your server designate the content-type as 'application/json' and encode it in json format if you can. Then when Backbone receives the JSON object it knows how to populate the model that requested it.

使用 SLIM PHP,路由的操作与上述非常相似.

With SLIM PHP, the routes operate pretty similarly to the above.

$app->post('/donut', function() use ($app) {
    // Code to create new donut
    // Returns a full donut resource with ID
});
$app->put('/donut/:id', function($id) use ($app) {
    // Code to update donut with id, $id
    $response = $app->response();
    $response->status(200);  // OK!
    // But you can send back other status like 400 which can trigger an error callback.
});
$app->delete('/donut/:id', function($id) use ($app) {
    // Code to delete donut with id, $id
    // Bye bye resource
});

所以你几乎完成了完整的往返旅程!去买苏打水.我喜欢Diet Mountain Dew.也给我拿一个.

So you've almost made the full round trip! Go get a soda. I like Diet Mountain Dew. Get one for me too.

一旦您的服务器处理了请求,对数据库和资源进行了处理,准备了响应(无论是简单的 http 状态编号还是完整的 JSON 资源),然后数据就会返回 Backbone 进行最终处理.

Once your server processes a request, does something with the database and resource, prepares a response (whether it be a simple http status number or full JSON resource), then the data comes back to Backbone for final processing.

使用 save()、fetch() 等方法 - 您可以添加关于成功和错误的可选回调.这是我如何设置这个特定蛋糕的示例:

With your save(), fetch(), etc. methods - you can add optional callbacks on success and error. Here is an example of how I set up this particular cake:

Cake = Backbone.Model.extend({
    defaults: {
        type: 'plain',
        nuts: false
    },
    url: 'cake'
});

myCake = new Cake();
myCake.toJSON()  // Shows us that it is a plain cake without nuts

myCake.save({type:'coconut', nuts:true}, {
    wait:true,
    success:function(model, response) {
        console.log('Successfully saved!');
    },
    error: function(model, error) {
        console.log(model.toJSON());
        console.log('error.responseText');
    }
});

// ASSUME my server is set up to respond with a status(403)
// ASSUME my server responds with string payload saying 'we don't like nuts'

这个例子有几个不同的地方.您会看到,对于我的蛋糕,我没有在保存之前设置 () 属性,而是简单地将新属性传递给我的保存调用.Backbone 非常擅长处理 JSON 数据并像冠军一样处理它.所以我想用椰子和坚果来保存我的蛋糕.(那是 2 个坚果吗?)无论如何,我将两个对象传递给我的保存.属性 JSON 对象和一些选项.第一个,{wait:true} 表示在服务器端行程成功之前不要更新我的客户端模型.当服务器成功返回响应时,将发生成功回调.但是,由于此示例导致错误(200 以外的状态将指示 Backbone 使用错误回调),因此我们获得了没有更改的模型表示.它应该仍然是简单的,没有坚果.我们还可以访问服务器发回的错误对象.我们发回了一个字符串,但它可能是具有更多属性的 JSON 错误对象.这位于 error.responseText 属性中.是的,我们不喜欢坚果."

There are a couple different things about this example that. You'll see that for my cake, instead of set() ing the attributes before save, I simply passed in the new attributes to my save call. Backbone is pretty ninja at taking JSON data all over the place and handling it like a champ. So I want to save my cake with coconuts and nuts. (Is that 2 nuts?) Anyway, I passed in two objects to my save. The attributes JSON object AND some options. The first, {wait:true} means don't update my client side model until the server side trip is successful. The success call back will occur when the server successfully returns a response. However, since this example results in an error (a status other than 200 will indicate to Backbone to use the error callback) we get a representation of the model without the changes. It should still be plain and without nuts. We also have access to the error object that the server sent back. We sent back a string but it could be JSON error object with more properties. This is located in the error.responseText attribute. Yeah, 'we don't like nuts.'

恭喜.您已经完成了从设置模型、在服务器端保存并返回的第一次相当完整的往返.我希望这个答案史诗能让您了解这一切是如何结合在一起的.当然,还有很多我正在浏览的细节,但是 Backbone 保存、RESTful 动词、服务器端操作、响应的基本思想都在这里.继续阅读 Backbone 文档(与其他文档相比,它非常容易阅读),但请记住,这需要时间来解决.你坚持得越多,你就会越流利.我每天都使用 Backbone 学习新东西,当你开始飞跃并看到你在这个框架中的流利程度不断提高时,它会变得非常有趣.:-)

Congratulations. You've made your first pretty full round trip from setting up a model, saving it server side, and back. I hope that this answer epic gives you an IDEA of how this all comes together. There are of course, lots of details that I'm cruising past but the basic ideas of Backbone save, RESTful verbs, Server-side actions, Response are here. Keep going through the Backbone documentation (which is super easy to read compared to other docs) but just keep in mind that this takes time to wrap your head around. The more you keep at it the more fluent you'll be. I learn something new with Backbone every day and it gets really fun as you start making leaps and see your fluency in this framework growing. :-)

可能有用的资源:

关于 SO 的其他类似答案:如何使用 Backbone 生成模型 ID

Other Similar Answers on SO: How to generate model IDs with Backbone

关于休息:http://rest.elkstein.org/http://www.infoq.com/articles/rest-introductionhttp://www.recessframework.org/page/towards-restful-php-5-basic-tips

这篇关于保存 Backbone.js 模型数据的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆