javascript - Backbone models and URL exceptions -
i have backbone model called user
has urlroot
of /api/users
. thus, if create new model id of 5, url /api/users/5
.
i have implemented endpoint individual user's twitter friends. endpoint /api/users/:id/twitter-friends
do need create new collection url
, , manually set id
, or can somehow create method on model make request , return new collection instance (of user's twitter friends). example:
var user = new user({ id: 5 }) user.findtwitterfriends() // returns collection of users
or, make unique collection data of sort:
var user = new user({ id: 5 }) var users = new users() users.url = user.url() + '/find-friends/twitter' // /api/users/5/find-friends/twitter users.fetch()
what best practice dealing urls in way? there better way? have similar needs other uses, such api endpoint can users username @ /api/users/username/:username
. having manually set urlroot:
var user = new user({ username: username }) user.urlroot = user.urlroot + '/username/' + username user.fetch()
perhaps should design urls differently? i'm open suggestions.
from experience best way override backbone.sync, in model.
looking @ backbone model.fetch! can see takes [options] . top of head would cleaner way. override backbone sync user, , let backbone handle getusers.
/* method redundant.i added show can add options go. */ getusers : function() { this.fetch({ action = 'getusers'; }); } getuser : function(username) { this.fetch({ action = 'getsingleuser'. username = username; }); }, sync : function(method, model, options) { if(method === 'read'){ if(options.action === 'getsingleuser') { this.url = '/username/' + options.username; } else this.url = '/find-friends/twitter'; ret = backbone.sync.apply(this, arguments); return ret; } else{ return backbone.sync.call(this, method, this, options); } }
Comments
Post a Comment