Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - How to override 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

backbone-localStorage

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

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

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.

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

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.

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"

[Edit]

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 is just the default global one that all models use unless the models have a sync method specifically set.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...