backbone.js use different urls for model save and fetch

前端 未结 4 1742
野性不改
野性不改 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:23

    Gingerhendrix's answer covers the bases, but I thought it was worth elaborating on the method for passing in an options value for save/delete/fetch.

    Instead of littering your code with urls every place you call one of those methods, you can also override the method on your model than then delegate back to the original Backbone.Model method like this:

    var MyModel = Backbone.Model.extend({
      save: function(attributes, options) {
        options = _.defaults((options || {}), {url: "http://your.save.url.com/"});
        return Backbone.Model.prototype.save.call(this, attributes, options);
      },
      // same thing for fetch and delete to give them different urls...
    }
    

    Then, you can call the method in your code without having to worry about remembering to set the url in the options.

提交回复
热议问题