Backbone.js:Collection.Get(id)->忽略大小写 [英] Backbone.js: Collection.Get(id) -> Ignore case
本文介绍了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
});
当我使用以下方法从集合中检索用户时:
When I retrieve a user from the collection using:
var myUser = collection.get(username);
用户名必须使用正确的大小写,否则我只会得到null.
the username has to be in the correct case, otherwise I just get null as a result.
是否有一种方法可以告诉主干忽略某些类似操作的情况?
Is there a way to tell backbone to ignore the case for certain operations like this on?
推荐答案
当然,您只需要更改相关代码即可.它位于 backbone.js
的 240-242
行上(适用于有记录的0.9.2版本):
Sure, you just need to change the relevant code. It is on lines 240-242
of backbone.js
(for documented 0.9.2 version):
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)];
}
},
这篇关于Backbone.js:Collection.Get(id)->忽略大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文