0
我有幾個觀察員模型,並在消除觀察員觀看Stefan Penner's talk後,我希望做同樣的mine:EmberJS:重構模型觀察員
import DS from "ember-data";
import Ember from "ember";
import TimeableMixin from "../mixins/timeable";
export default DS.Model.extend(TimeableMixin, {
employer: DS.belongsTo("company", {async: true}),
updateDescription: function() {
let description = "";
const hasOccupation = !Ember.isBlank(this.get("occupation")),
hasEmployer = !Ember.isBlank(this.get("employer.name"));
if (hasOccupation) {
description += this.get("occupation");
}
else {
if (this.get("type")) {
description += `${Ember.String.capitalize(this.get("type"))} Job`;
}
else {
description = "Full-time Job"; // we have to hard-code the default, because of async behaviour
}
}
if (hasEmployer) {
description += ` at ${this.get("employer.name")}`;
}
this.get("income").then((resolvedIncome) => {
resolvedIncome.set("description", description);
});
}.observes("employer.name", "occupation", "type"),
occupation: DS.attr("string"),
income: DS.belongsTo("income", {async: true}), /* Annual income ($) */
incomeChanged: function() {
if (this.get("isHourly")) {
let hourlyRate = parseInt(this.get("hourlyRate")), weeklyHours = parseInt(this.get("weeklyHours"));
if (hourlyRate && weeklyHours) {
let yearlySalary = (hourlyRate * weeklyHours) * 52.1775; // there are 52.1775 weeks in a year
this.get("income").then((resolvedIncome) => {
resolvedIncome.set("value", yearlySalary);
});
}
}
}.observes("hourlyRate", "weeklyHours"),
// ...
});
我已經考慮到「行動類似的東西下來,數據上升」,其中控制器或組件可能處理這樣的計算性能:
export default Ember.Component.extend({
updatedDescription: Ember.computed("employment.employer.name", "employment.occupation", "employment.type", function() {
let description = "";
const hasOccupation = !Ember.isBlank(this.get("occupation")),
hasEmployer = !Ember.isBlank(this.get("employer.name"));
if (hasOccupation) {
description += this.get("occupation");
}
else {
if (this.get("type")) {
description += `${Ember.String.capitalize(this.get("type"))} Job`;
}
else {
description = "Full-time Job"; // we have to hard-code the default, because of async behaviour
}
}
if (hasEmployer) {
description += ` at ${this.get("employer.name")}`;
}
return description;
}),
employment: null,
// ...
});
但是,這將防止設置在我的模型,它最初是什麼,我所要做的description
財產。
我該如何重構模型觀察者以使用計算屬性並將其刪除?
這不會爲計算出的屬性返回任何值。鑑於你的例子,看起來你**是**在一個計算屬性中設置''description''屬性... – user1429980
對不起,忘記了回報。固定。 – NicholasJohn16