博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
backbone 学习之sync
阅读量:6463 次
发布时间:2019-06-23

本文共 4072 字,大约阅读时间需要 13 分钟。

sync 是 Backbone 每次向服务器读取或保存模型时都要调用执行的函数。 默认情况下,它使用 (jQuery/Zepto).ajax 方法请求。 如果想采用其他的方案也可以,比如 WebSockets, XML, 或 Local Storage,我们可以重载该函数即可大道我们的需要。

下面分析下它的代码逻辑:

// Backbone.sync  // -------------  // Override this function to change the manner in which Backbone persists  // models to the server. You will be passed the type of request, and the  // model in question. By default, makes a RESTful Ajax request  // to the model's `url()`. Some possible customizations could be:  //  // * Use `setTimeout` to batch rapid-fire updates into a single request.  // * Send up the models as XML instead of JSON.  // * Persist models via WebSockets instead of Ajax.  //  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests  // as `POST`, with a `_method` parameter containing the true HTTP method,  // as well as all requests with the body as `application/x-www-form-urlencoded`  // instead of `application/json` with the model in a param named `model`.  // Useful when interfacing with server-side languages like **PHP** that make  // it difficult to read the body of `PUT` requests.  Backbone.sync = function(method, model, options) {    var type = methodMap[method];    // Default options, unless specified.    _.defaults(options || (options = {}), {      emulateHTTP: Backbone.emulateHTTP,      emulateJSON: Backbone.emulateJSON    });    // Default JSON-request options.    var params = {type: type, dataType: 'json'};    // Ensure that we have a URL.    // 确保有url 没在option中的话 从model获取    if (!options.url) {      params.url = _.result(model, 'url') || urlError();    }    // Ensure that we have the appropriate request data.    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {      params.contentType = 'application/json';      params.data = JSON.stringify(options.attrs || model.toJSON(options));    }    // For older servers, emulate JSON by encoding the request into an HTML-form.    if (options.emulateJSON) {      params.contentType = 'application/x-www-form-urlencoded';      params.data = params.data ? {model: params.data} : {};    }    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`    // And an `X-HTTP-Method-Override` header.    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {      params.type = 'POST';      if (options.emulateJSON) params.data._method = type;      // 在请求之前需要做的处理      var beforeSend = options.beforeSend;      options.beforeSend = function(xhr) {        xhr.setRequestHeader('X-HTTP-Method-Override', type);        if (beforeSend) return beforeSend.apply(this, arguments);      };    }    // Don't process data on a non-GET request.    if (params.type !== 'GET' && !options.emulateJSON) {      params.processData = false;    }    // If we're sending a `PATCH` request, and we're in an old Internet Explorer    // that still has ActiveX enabled by default, override jQuery to use that    // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.    // 兼容jquery的patch请求    if (params.type === 'PATCH' && window.ActiveXObject &&          !(window.external && window.external.msActiveXFilteringEnabled)) {      params.xhr = function() {        return new ActiveXObject("Microsoft.XMLHTTP");      };    }    // Make the request, allowing the user to override any Ajax options.    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));    model.trigger('request', model, xhr, options);// 触发request请求    return xhr;  };  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.  var methodMap = {    'create': 'POST',    'update': 'PUT',    'patch':  'PATCH',    'delete': 'DELETE',    'read':   'GET'  };  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.  // Override this if you'd like to use a different library.  // 默认jquery zepto的ajax请求  Backbone.ajax = function() {    return Backbone.$.ajax.apply(Backbone.$, arguments);  };

 

欢迎指导、纠错、建议。

转载于:https://www.cnblogs.com/xiaobudiandian/archive/2013/03/21/Backbone_sync.html

你可能感兴趣的文章
linux中yum源安装dhcp,24.Linux系统下动态网络源部署方法(dhcpd)
查看>>
ASP.NET性能优化之分布式Session
查看>>
转载:《TypeScript 中文入门教程》 16、Symbols
查看>>
C#技术------垃圾回收机制(GC)
查看>>
漫谈并发编程(三):共享受限资源
查看>>
【转】github如何删除一个仓库
查看>>
Linux系统编程——进程调度浅析
查看>>
大数据Lambda架构
查看>>
openCV_java 图像二值化
查看>>
状态模式
查看>>
删除CentOS / RHEL的库和配置文件(Repositories and configuraiton files)
查看>>
VC++获得微秒级时间的方法与技巧探讨(转)
查看>>
HDOJ-1010 Tempter of the Bone
查看>>
MySQL my.cnf参数配置优化详解
查看>>
JavaNIO基础02-缓存区基础
查看>>
日本开设无人机专业,打造无人机“人才市场”
查看>>
190行代码实现mvvm模式
查看>>
PXE部署实例
查看>>
cobbler初探------实现自动安装centos6.4
查看>>
Android Studio 2.0 preview3 BUG
查看>>