Search code examples
backbone.jscoffeescriptthorax.js

Backbone get model not by ID


I have a backbone model of a patient, which I can use to pull patients from my Mongo database. But in addition to polling them by ID, I would like to be able to pull them by name. The only way I could think of doing this is to do something like:

class Thorax.Models.Patient extends Thorax.Model
  urlRoot: '/api/patients'
  idAttribute: '_id'
  fetch: (options = {}) ->
    if @get 'first' # has first name, lookup by that instead of id
      @urlRoot = '/api/patients/by_name/' + (@get 'first') + '/' + (@get 'last')
      @set '_id', ''
    super options

But overriding the urlRoot seems bad. Is there another way to do this?


Solution

  • you may just use Backbone.Model#url as a method and apply all your logic there. So if it is first name in the model use one url and else use default url root.

    Here is jsbin code for this (just convert to your CoffeeScript) You may open network tab to see 2 XHR requests for 2 models I created they are different.

    var Model = Backbone.Model.extend({
      urlRoot: 'your/url/root',
    
      url: function() {
        // If model has first name override url to lookup by first and last
        if (this.get("first")) {
          return '/api/patients/by_name/' + encodeURIComponent(this.get('first')) + '/' + encodeURIComponent(this.get('last'));
        }
    
        // Return default url root in other cases
        return Backbone.Model.prototype.url.apply(this, arguments);
       }
    });
    
    (new Model({ id: 1, first: 'Eugene', last: 'Glova'})).fetch();
    (new Model({ id: "patient-id"})).fetch();
    

    Also you may apply this logic to the url in fetch options. But I don't think it is good way. Happy coding.