在 Backbone.js 中覆盖 Model.get(attr) 的最佳方法是什么? [英] What's the best way to override Model.get(attr) in Backbone.js?
问题描述
我是第一次使用 Backbone.js,到目前为止我很喜欢它.我目前无法在模型的动态属性中解决一件事.例如,假设我有一个 Person 模型,我想获取他们的全名:
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');
}
});
然后我可以做person.getFullName()
.但我想让它与其他 getter 保持一致,更像是 person.get('fullName')
.如果不凌乱地覆盖 Person#get,我不知道如何做到这一点.还是那是我唯一的选择?
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.
推荐答案
这会更简单吗?
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?
这篇关于在 Backbone.js 中覆盖 Model.get(attr) 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!