2014-10-20 107 views
0

我有一个病人的骨干模型,我可以用它来从我的Mongo数据库中提取病人。但除了通过身份证进行投票之外,我希望能够通过名称将其拉出来。我能想到的唯一办法就是做类似这样的事情:骨干不通过ID得到模型

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 

但是重写u​​rlRoot看起来很糟糕。有没有另一种方法来做到这一点?

回答

0

您可能只需要使用Backbone.Model#url作为一种方法并在其中应用您的所有逻辑。 因此,如果它是模型中的第一个名称,则使用一个url,否则使用默认的url root。

下面是该jsbin代码(只是转换到你的CoffeeScript) 您可以打开网络标签,查看2款我创建它们是不同的2个XHR请求。

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(); 

你也可以在fetch选项适用这个逻辑到url。但我认为这不是好方法。 快乐编码。