2012-07-26 86 views
0

我有以下的模型和集合:Backbone.js的:Collection.Get(ID) - >忽略大小寫

var UserModel = Backbone.Model.extend({ 
    url: 'api/user', 
    idAttribute:'username', 
    defaults: { 
     username:'', 
     password:'', 
     email:'', 
     tags:'' 
    } 
}); 
var UserCollection= Backbone.Collection.extend({ 
    url: 'api/user', 
    model: UserModel 
}); 

當我使用檢索收集用戶:

var myUser = collection.get(username); 

的用戶名必須是正確的,否則我只會得到空值。

有沒有辦法告訴骨幹忽略這種情況下的某些操作呢?

回答

1

當然,你只需要改變相關的代碼。它是在線路的backbone.js240-242(用於記錄0.9.2版本):

get: function(attr) { 
    return this.attributes[attr]; 
}, 

更改它像到:

get: function(attr) { 
    // will skip if null or undefined -- http://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-which-method-is-better 
    if (this.attributes[attr] != null) { 
     return this.attributes[attr]; 
    } 
    // and then try to return for capitalized version -- http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript 
    else {   
     return this.attributes[attr.charAt(0).toUpperCase() + attr.slice(1)]; 
    } 
}, 

收集改變

get: function(id) { 
    if (id == null) return void 0; 
    return this._byId[id.id != null ? id.id : id]; 
}, 

到這樣的事情可能工作:

get: function(id) { 
    if (id == null) return void 0; 
    var firstCase = this._byId[id.id != null ? id.id : id]; 
    if (firstCase != null) { 
     return firstCase; 
    } 
    else { 
     return this._byId[capitalize(id.id) != null ? capitalize(id.id) : capitalize(id)]; 
    } 
}, 
+0

很酷。謝謝我完全忘記了重寫標準行爲是多麼容易。 – AyKarsi 2012-07-26 08:11:58

+2

更好的方法是使用'Backbone.Model.extend({})'並覆蓋那裏的'get'。您可以代理'Backbone.Model.prototype.get.call(this,lowercaseId)'並確保正確的行爲。 – 2013-12-05 15:01:22