开发者

How do I specify various URLs in a backbone app?

I need one of my backbone models to hit a variety of URLs depending on the type of action being performed. How do I determine the action within 开发者_如何学编程the URL function so that I can specify the appropriate URL? For example:

DELETE: /myapipath/itemtype/id/

POST: /myapipath/special-path/

GET: /myapipath/special-path/?code=ABC

I know how to tell the difference between a POST and everything else: this.isNew()

But how do I tell the difference between a DELETE and a GET in a custom model.url function?

Please don't suggest that I change the server-side api. That isn't up to me.

Thanks!


Conceptually the url of a Backbone model is the primary GET url of the resource. To use a different url for some of the actions, override the model's sync function. Fortunately, Backbone makes it easy to override:

window.MyModel = Backbone.Model.extend({
  // ... other stuff ...

  url: '/myapipath/special-path/?code=ABC',

  methodUrl: {
    'create': '/myapipath/special-path/',
    'delete': '/myapipath/itemtype/id/'
  },

  sync: function(method, model, options) {
    if (model.methodUrl && model.methodUrl[method.toLowerCase()]) {
      options = options || {};
      options.url = model.methodUrl[method.toLowerCase()];
    }
    Backbone.sync(method, model, options);
  }
}

Edit: I took another look at the Backbone source and noticed that it merges the whole options argument to build the params, not options.params, and updated my example accordingly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜