如何覆盖Backbone.sync? [英] How to override Backbone.sync?

查看:161
本文介绍了如何覆盖Backbone.sync?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出来Backbone.js的,和的事情我想一个是作出一个远程API的调用,所以我需要能够覆盖Backbone.sync,据我了解的文档

I'm trying out Backbone.js, and one of the things I'm trying is to make a call to a remote API, so I need to be able to override Backbone.sync, as I understand the documentation.

有没有如何做到这一点的文档本身的例子,似乎没有成为谷歌组骨干......可以有人指出,这样做的例子吗?

There isn't an example of how to do that in the documentation itself, and there doesn't appear to be a google group for Backbone... can someone point out an example for doing this?

推荐答案

看看这个注释的源代码例子,它们将覆盖 Backbone.sync 带的localStorage替代

Take a look at this annotated source example where they overwrite Backbone.sync with a localstorage alternative

骨干网的localStorage

基本上Backbone.sync应该是一个函数,有4个参数:

Basically Backbone.sync should be a function that takes 4 arguments:

Backbone.sync = function(method, model, options) { };

您需要解雇或者 options.success options.error 取决于是否成功。该方法的格式为:

You need to fire either options.success or options.error depending on whether the method succeeded. The methods are in the format:


  • 创造:期望你在服务器上创建的模型

  • :期望你从服务器读取这个模型,并将其返回

  • 更新:期望你的说法更新服务器上的模型

  • 删除:预计从服务器中删除模型

  • "create" : expected that you create the model on the server
  • "read" : expected that you read this model from the server and return it
  • "update" : expected that you update the model on the server with the argument
  • "delete" : expected that you delete the model from the server.

您需要实现的4种方法,并定义任何你想为你的服务器

You need to implement those 4 methods and define whatever you want for your "server"

当然,这些仅仅是事情 Backbone.sync 必须的实施。您可能会实施更多方法键,你可以把更多的PARAMATERS回成功但最好不要这样做。

Of course these are only the things that Backbone.sync must implement. You may implement more methods and you may pass more paramaters back to success but it's best not to do this.

这是最好的,以确保它不一样的 Backbone.sync 目前是否让你面向接口编程而不是一个实现。如果你想转出修改后的 Backbone.sync 为说localStorage的一个你不会有自己扩展它以符合您的扩展Backbone.sync

It's best to make sure it does the same as Backbone.sync does currently so that your programming to an interface rather then an implementation. If you want to switch out your modified Backbone.sync for say the localStorage one you won't have to extend it yourself to match your extended Backbone.sync"

也不要注意,您可以使用同步的多种实现。到 Backbone.sync 每个参考actaully (this.sync || Backbone.sync),所以你只需要做是这样的:

Also do note that you can use multiple implementations of sync. Every reference to Backbone.sync is actaully (this.sync || Backbone.sync) so you just have to do something like:

var MyModel = Backbone.Model.extend({ 
    ...

    "sync": myOwnSpecificSync,

    ...
});

Backbone.sync 只是缺省全局所有机型使用,除非该机型有一个同步具体方法集。

Backbone.sync is just the default global one that all models use unless the models have a sync method specifically set.

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

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