javascript - Prepend absolute URL path in Backbone.sync for an API on another server -


my backbone app communicates api exists on server. backbone.sync generate relative urls default. simplest way prepend absolute server path following:

myapp.base_url = "https://api.someothersite.com"   class myapp.model extends backbone.model   urlroot: "#{myapp.base_url}/my_app_url" 

however, i'd rather not isn't dry. thought try following overriding 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 

however, problematic other parts of code options object gets passed around on place. *(explanation interested @ bottom)

is there recommended clean , dry way prepend server path front of urls generated backbone.sync?


*if model being synced instance of backbone.collection options object passed collection's model constructor. url 1 of few properties directly attached model if passed in part of options object. breaks sync models created in collection have set url attached them instead of url method generates appropriate url using urlroot or collection's url.

i think best option create base model other models extend from:

myapp.model = backbone.model.extend({   urlroot: function(){              return 'https://api.someothersite.com/' + this.get('urlfragment')   } }); 

and have models defined so

myapp.mymodel = myapp.model.extend({   urlfragment: "my_model_url" }) 

so, in coffeescript:

class myapp.model extends backbone.model   urlroot: ->            'https://api.someothersite.com/' + @get('urlfragment') 

and

class myapp.mymodel extends myapp.model   urlfragment: "my_model_url" 

now you've got urls specified in dry fashion!


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -