backbone.js use different urls for model save and fetch

前端 未结 4 1749
野性不改
野性不改 2020-12-22 23:44

My back-end has two separate pages, one for handling the model save request and the other for model fetch.

What is the best approach for calling save() and fetch()

4条回答
  •  长情又很酷
    2020-12-23 00:29

    If you're reading the source you probably already have a working solution. You essentially have two options (probably more)-

    1. Pass URL in save()/fetch()

    save() takes two parameters attr and options attr - is a hash of model attributes and is used to update the model before save. eg.

    myModel.save(attrs)
    

    is equivalent to

    myModel.set(attrs)
    myModel.save()
    

    The second parameter is an options hash, which is passed down to this.sync() (and then Backbone.sync and then $.ajax) - setting the url in this hash will work as expected. You can pass false, undefined, or {} as the first parameter to skip the update.

    1. Override Backbone.sync

    Rather than have url's scattered throughout your code every time you call save() or fetch() write your own sync function to compute the url for you, the delegate to the original Backbone.sync to do the heavy lifting

    eg. (This sync function adds /save to the url on CREATE, UPDATE and DELETE actions)

    function mySyncFunction(method, model, options){
      if(method=='GET'){
        options.url = model.url; 
      }else{
         options.url = model.url + '/save'; 
      }
      return Backbone.sync(method, model, options);
    }
    

    To use your custom sync method just declare it as part of your model

    var myModel = Backbone.Model.extend({ 
      ...
    
      "sync": mySyncFunction,
    
      ...
    });
    

提交回复
热议问题