Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Backbone.js:Collection.Get(id)->;忽略案例_Backbone.js - Fatal编程技术网

Backbone.js:Collection.Get(id)->;忽略案例

Backbone.js:Collection.Get(id)->;忽略案例,backbone.js,Backbone.js,我有以下型号和系列: var UserModel = Backbone.Model.extend({ url: 'api/user', idAttribute:'username', defaults: { username:'', password:'', email:'', tags:'' } }); var UserCollection= Backbone.Collection.extend({

我有以下型号和系列:

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


有没有一种方法可以告诉主干网,对于像这样的操作,忽略案例?

当然,您只需要更改相关代码。它位于
backbone.js
240-242
行(对于文档化的0.9.2版本):

将其更改为:

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.Model.extend({})
并覆盖那里的
get
。您可以代理到
Backbone.Model.prototype.get.call(this,lowercaseId)
并确保行为正确。
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)];
  }
},