0

从风格上讲,我不确定在 JavaScript 中处理这种情况的最佳方式。

我们从这个开始获取之前模型的副本(如果可用)。然后,如果可用,我将根据这些值创建一个 DamageDiagnosisModel。

this._previousModel = this.impairmentsCollection.get(this.model.get('id')) || '';

选项1:

this._impairmentDiagnosisModel = new ImpairmentDiagnosisModel({
    id: this.model.get('id'),
    cdx: (this._previousModel && this._previousModel.get('diagnosis').cdx) || _.first(this._diagnosisClass).id,
    nonKeyFactor: this._previousModel && this._previousModel.get('diagnosis').nonKeyFactor,
    impairmentValue: this._previousModel && this._previousModel.get('diagnosis').impairmentValue,
    side: this._previousModel && this._previousModel.get('diagnosis').side,
    digit: this._previousModel && this._previousModel.get('diagnosis').digit
});

选项 2:

if(this._previousModel) {
    this._impairmentDiagnosisModel = new ImpairmentDiagnosisModel({
        id: this.model.get('id'),
        cdx: this._previousModel.get('diagnosis').cdx,
        nonKeyFactor: this._previousModel.get('diagnosis').nonKeyFactor,
        impairmentValue: this._previousModel.get('diagnosis').impairmentValue,
        side: this._previousModel.get('diagnosis').side,
        digit: this._previousModel.get('diagnosis').digit
    });
}
else {
    this._impairmentDiagnosisModel = new ImpairmentDiagnosisModel({
        id: this.model.get('id'),
        cdx: _.first(this._diagnosisClass).id
    });
}

使用选项#1,它会在模型​​中添加不必要的空属性,但这在这里无关紧要。如果服务器接收到空属性,它们将被忽略。

使用选项#2,它的代码更多,更易于阅读,但似乎效率低下。

在这种情况下,首选方法是什么?

4

1 回答 1

2

选项 3:您可以克隆您的_previousModel.get('diagnosis')对象,然后对其进行修改以添加自定义属性。

例如,

var data = (this._previousModel) ? _.clone(this._previousModel.get('diagnosis')) : {};
data.id = this.model.get('id');
data.cdx = data.cdx || _.first(this._diagnosisClass).id;

this._impairmentDiagnosisModel = new ImpairmentDiagnosisModel(data);
于 2013-01-10T17:14:32.160 回答