如何拯救Backbone.js的模型数据? [英] Ways to save Backbone.js model data?

查看:129
本文介绍了如何拯救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.

推荐答案

基本上模型有一个属性称为属性这是一定的模式可能有不同的价值观。骨干网使用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
    }
});

要填充的模型中,有几个方法可以做到这一点。例如,您可以通过在JSON或使用方法调用集传递(),接受属性的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 / REST风格的?它是一种很难在这里解释这一切在短期Blurb的。特别是关于REST和骨干储蓄,那东西来包装你的脑袋周围是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信息的请求。 GET和POST。在RESTful的环境中,这些动词有特定的使用了骨干承担特殊的意义。当你想从服务器获得一定的资源(例如甜甜圈模型我救了最后一次,一个博客条目,计算机规范)和资源存在,你做一个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.

在我进入骨干,我从来没有碰过以下两种HTTP请求方法。 PUT和DELETE。这两个动词也有特定的含义骨干。当你想更新资源(例如更改甜甜圈柠檬柠檬到甜甜圈等的味道),你使用一个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.

这些基础是非常重要的,因为你的REST风格的应用程序,你可能会有一个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

如果我做一个GET到URI,它将获得甜甜圈模型的17.一个ID: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的新的数据,我会更新它,节省了过去。如果我删除该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设计都是由你,你如何看待你的资源。但对于REST风格的设计,我的理解是,你要保持你的行动,你的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? :-)

因此​​,让我们回想着骨干。主干是美妙的,因为它做了很多工作,为你。为了拯救我们的甜甜圈和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();

骨干是聪明的。如果你只是创建了一个甜甜圈的资源,它不会有来自服务器的ID。它有一种叫做CID这就是骨干内部使用,但因为它没有正式身份证它知道应该创建一个新的资源,并将其发送POST请求。如果你从服务器模型,它可能有一个ID,如果所有是正确的。在这种情况下,当您保存()骨干假设你想要更新的服务器,它会发送一个PUT。为了得到一个特定的资源,你会使用的方法骨干.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.

在previous例子,我从来没有明确告诉骨干,其中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

骨干网会得到 HTTP的thirdHelping://本地主机:8888 /甜甜圈/ 15 它会简单地添加/甜甜圈干到你的站点根目录

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

如果你在我身边STILL,不错。我认为。除非你困惑。但我们会反正跋涉。这第二部分是服务器端。我们已经讨论过的HTTP动词的不同以及动词后面的语义含义。含义你,骨干,你的服务器必须共享。

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://本地主机:8888 /甜甜圈/ 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服务端code。有些人喜欢红宝石,有人喜欢.NET,我喜欢PHP。我特别喜欢苗条的PHP微架构。 SLIM PHP是一种微型的框架,具有处理REST风格的活动,一个非常优雅和简单的工具集。您可以在实例定义路由(URI)来像上面并根据呼叫是否是GET,POST,PUT或DELETE它将执行正确的code。类似的还有苗条状的凹槽,进补其他解决方案。相信喜欢蛋糕和codeIgniter更大的框架也做类​​似的事情,虽然我很喜欢微乎其微。我说过我喜欢苗条? ; - )

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? ;-)

这是在服务器上的什么摘录code可能看起来(即特别是关于路由。)

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));
});

这里要注意的骨干预计JSON对象是很重要的。总是有你的服务器,如果你可以指定内容类型为应用程序/ JSON'和连接code将其以JSON格式。然后,当骨干收到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.

使用PHP SLIM,航线操作类似pretty以上。

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
});

所以,你几乎让全往返!去获得苏打水。我喜欢饮食山露水。获取一个对我来说。

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

一旦你的服务器处理的请求,确实与数据库和资源,prepares的响应(无论是一个简单的HTTP状态数或全JSON资源)的东西,然后将数据回来骨干进行最后的处理。

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.

通过您的保存(),取()等方法 - 你可以添加成功和错误可选回调。下面是我如何设置这个特殊的蛋糕的例子:

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'

有关于这个例子,一对夫妇不同的东西。你会看到,我的蛋糕,而不是集()ING属性保存之前,我只是在新的属性传递给我节省电话。主干是采取JSON数据所有的地方和处理它像一个冠军pretty忍者。所以,我要救我的蛋糕椰子和坚果。 (是2个螺母?)反正,我中有两个对象传递给我的拯救。属性JSON对象和一些选项。第一,{等待:真正}的意思,直到服务器一面之旅是成功不更新自己的客户端模式。成功调用当服务器成功返回响应后面会发生。然而,由于这个例子中导致错误(超过200以外的状态将指示骨干使用错误回调),我们得到的模型的重新presentation没有变化。它应该仍然是普通的,无螺母。我们还可以访问服务器发回的错误对象。我们发回一个字符串,但它可能是与多个属性JS​​ON错误对象。这是位于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.'

恭喜。你从建立模型,保存服务器端,然后回到了你的第一个pretty全往返。我希望这个答案史诗给你这一切是如何走到一起的想法。当然有,很多是我过去巡航细节,但主干的基本思路保存,REST风格的动词,服务器端的操作,反应都在这里。请通过骨干文档去(这是超级容易相比其他文档阅读)只是要记住,这需要时间来回绕你的头。你越坚持下去越流畅,你会没事的。我每天都学会骨干新的东西,当你开始做跳跃,看看你的流畅度在这个框架内不断增长的它变得非常有趣。 : - )

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. :-)

编程快乐!

编辑:资源可能是有用的:

Resources that may be useful:

其它类似的答案:
如何生成与骨干型号ID

在REST:
http://rest.elkstein.org/
<一href=\"http://www.infoq.com/articles/rest-introduction\">http://www.infoq.com/articles/rest-introduction
<一href=\"http://www.recessframework.org/page/towards-restful-php-5-basic-tips\">http://www.recessframework.org/page/towards-restful-php-5-basic-tips

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

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