What's the best way to override Model.get(attr) in Backbone.js?
backbone.js, javascript
Solution
Would this be simpler?
var Person = Backbone.Model.extend({
get: function (attr) {
if (typeof this[attr] == 'function')
{
return this[attr]();
}
return Backbone.Model.prototype.get.call(this, attr);
}
});
This way you could also override existing attributes with functions. What do you think?
Problem
I'm using Backbone.js for the first time, and liking it so far. One thing I can't work out at the moment in dynamic attributes of models. For example, say I have a Person model, and I want to get their full name: ``` var Person = Backbone.Model.extend({ getFullName: function () { return this.get('firstName') + ' ' + this.get('surname'); } }); ``` Then I could do `person.getFullName()`. But I'd like to keep it consistent with the other getters, more like `person.get('fullName')`. I don't see how to do that without messily overriding Person#get. Or is that my only option? This is what I've got so far for the overriding option: ``` var Person = Backbone.Model.extend({ get: function (attr) { switch (attr) { case 'fullName': return this.get('firstName') + ' ' + this.get('surname'); break; case 'somethingElse': return this.doSomethingClever(); break; default: return Backbone.Model.prototype.get.call(this, attr); } } }); ``` I suppose it's not terrible, but it seems there should be a better way.