简体   繁体   中英

Backbone/Backbone-Relational with Custom Sync

I am working on a Backbone.js app. I am also using a 3rd party API to access my data in the app. This 3rd party API does not provide the standard REST interface that Backbone expects.

I have heard that I can extend or overload the Backbone.Sync function to make Backbone work with the 3rd party API, but I have not been able to find any examples to determine how this might be done.

Does anyone know of any examples or tutorials available for this? Can anyone provide an example?

Also, I recently discovered Backbone-Relational, which may come in handy in my application as well as my data is relational. However, I am concerned that using Backbone-Relational with a custom Backbone.Sync function may cause problems as well. Does anyone have any experience with this?

Generally speaking, you write custom functions that perform the basic CRUD operations using your 3rd party API, then overwrite Backbone.sync to switch on the method to use.

Backbone.sync = function(method, model, options){
  switch(method) {
    case 'create':
      console.log('Creating: ', model);
      break;
    case 'read':
      console.log('Reading: ', model);
      break;
    case 'update':
      console.log('Updating: ', model);
      break;
    case 'destroy':
      console.log('Destroying: ', model);
      break;
}

For more depth and a walkthrough, check out DailyJS's Backbone+RequireJS+GoogleAPI's tutorial, specifically part 2 and part 4 .

For another example, check out the source code of the Backbone localStorage adapter , as it overwrites Backbone.sync to persist to localStorage instead of across the network.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM