另一个服务器上的API中Backbone.sync prePEND绝对URL路径 [英] Prepend absolute URL path in Backbone.sync for an API on another server

查看:68
本文介绍了另一个服务器上的API中Backbone.sync prePEND绝对URL路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的骨干应用程序与另一台服务器上存在的API进行通信。 Backbone.sync 将默认生成的是相对URL。以prePEND绝对的服务器路径最简单的方法是类似以下内容:

My Backbone app communicates with an API that exists on another server. Backbone.sync will generate relative URLs by default. The simplest way to prepend the absolute server path would be something like the following:

MyApp.BASE_URL = "https://api.someOtherSite.com"


class MyApp.Model extends Backbone.Model
  urlRoot: "#{MyApp.BASE_URL}/my_app_url"

不过,我宁愿不这样做,因为它是不干燥。我以为我可以通过重写 Backbone.sync 尝试类似以下内容:

do (Backbone) ->
  BASE_URL = 'https://api.someOtherSite.com'
  baseSync = Backbone.sync

  Backbone.sync = (method, model, options) ->
    url = _.result(model, 'url')
    options.url = "#{BASE_URL}/#{url}" if url && !options.url

    baseSync method, model, options

不过,这是因为对象被传来传去所有的地方的选项code的其他部分存在问题。 *(底部解释有兴趣的)

However, this is problematic for other parts of the code as the options object gets passed around all over the place. *(explanation for the interested at the bottom)

有没有推荐的清洁和干燥方式prePEND服务器的路径由 Backbone.sync

Is there a recommended clean and DRY way to prepend a server path to the front of all URLs generated by Backbone.sync?

*如果模式正在同步是 Backbone.Collection 选项实例对象将得到传递到集合的模型构造。网址是,如果将它传递作为的选项对象的一部分获得直接连接到一个模型中的几个属性之一。这打破同步对于那些在集合中创建的,因为他们现在有一组URL连接到他们,而不是网​​址的任何模型方法,通过使用产生一个适当的URL urlRoot 或集合的网​​址

*If the model being synced is an instance of Backbone.Collection this options object will get passed to the collection's model constructor. URL is one of the few properties that will get directly attached to a model if it is passed in as a part of the options object. This breaks sync for any models that are created in a collection as they now have a set URL attached to them instead of a url method that generates an appropriate url by using urlRoot or the collection's url.

推荐答案

我认为最好的办法是建立一个示范基地,你的其他车型将扩展:

I think the best option is to create a base model that your other models will extend from:

MyApp.Model = Backbone.Model.extend({
  urlRoot: function(){
             return 'https://api.someOtherSite.com/' + this.get('urlFragment')
  }
});

,然后让你的模型中,像这样定义

And then have your models be defined like so

MyApp.MyModel = MyApp.Model.extend({
  urlFragment: "my_model_url"
})

所以,在CoffeeScript的:

So, in CoffeeScript:

class MyApp.Model extends Backbone.Model
  urlRoot: ->
           'https://api.someOtherSite.com/' + @get('urlFragment')

class MyApp.MyModel extends MyApp.Model
  urlFragment: "my_model_url"

现在你有你在干燥的方式指定的URL!

Now you've got your urls specified in a DRY fashion!

这篇关于另一个服务器上的API中Backbone.sync prePEND绝对URL路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆