是什么在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()
。但我想保持它与其他干将一致,更像 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屋!