---
title: "Backbone.sync-将模型同步到服务器"
author: "zhouyrt"
date: "2014-05-05T10:52:21Z"
tags: []
categories: ["Web前端"]
slug: "backbone-sync"
draft: false
lastmod: "2014-05-05T10:52:21Z"
id: 2059983
url: "https://snandy.iteye.com/blog/2059983"
---

默认情况下，只要保存模型（Model/Collection的sync方法），Backbone就会Ajax请求把模型持久化到服务器端。

 

###### 有以下几点

1. sync方法把model持久化存储到服务器端，你可以重写该方法的实现方式，它默认使用jQuery或zepto的[$.ajax](http://api.jquery.com/jQuery.ajax/)
2. 整个Backbone，只有Model和Collection的sync会调用Backbone.sync
3. 请求类型由第一个参数method决定，可以是create/update/patch/delete/read。它默认采用[RESTful](http://zh.wikipedia.org/wiki/REST)请求
4. 请求的数据由第二个参数model决定，URL默认是model的url，数据是model的attributes转成JSON。数据类型默认是JSON类型
5. 请求后会触发model的request的事件，如果添加了该事件的handler后

 

###### 执行流程

1. 处理type，从methodMap
2. 初始化options
3. 初始化params，含type/dataType/url
4. create/update/patch时，params的contentType为application/json，params.data确保有值，值为model转为json
5. emulateJSON
6. mimicking HTTP
7. 非GET时， processData为false
8. PATCH时 IE低版本重写xhr
9. 触发request事件

 

###### **附图**

![](http://dl2.iteye.com/upload/attachment/0096/7681/81d5c1da-2bac-3d7f-8bd2-61e52fb2b0aa.png)  
 

 

相关：

[http://www.ruanyifeng.com/blog/2011/09/restful.html](http://www.ruanyifeng.com/blog/2011/09/restful.html)

 

**附图**