0

我有以下模型和集合:

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

用户名必须是正确的大小写,否则我只会得到 null 结果。

有没有办法告诉骨干忽略这样的某些操作的情况?

4

1 回答 1

1

当然,您只需要更改相关代码即可。它位于以下行240-242backbone.js对于记录的 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)];
  }
},
于 2012-07-26T07:54:00.597 回答