0

I have the following model and collection:

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

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?

AyKarsi
  • 9,435
  • 10
  • 54
  • 92

1 Answers1

1

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];
},

Change it something like to:

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)];
   }
},

for collection changing

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

to something like this might work:

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)];
  }
},
ipavlic
  • 4,906
  • 10
  • 40
  • 77
  • 2
    A better approach would be to use `Backbone.Model.extend({})` and override the `get` there. You can proxy to `Backbone.Model.prototype.get.call(this, lowercaseId)` and be assured of correct behavior. – Platinum Azure Dec 05 '13 at 15:01