我有两节课:
export class Enrollment {
private _productId = signal(0);
private _price = signal(0);
public productId = this._productId.asReadonly();
public price = this._price.asReadonly();
public setProductId(productId: number): void {
this._productId.set(productId);
}
public setPrice(price: number): void {
this._price.set(price);
}
}
export class Cart {
private _enrollments = signal<Enrollment[]>([]);
public enrollments = this._enrollments.asReadonly();
public addToCart(enrollment: Enrollment): void {
this._enrollments.set([...this._enrollments(), enrollment]);
}
public removeFromCart(enrollment: Enrollment): void {
this._enrollments.set(this._enrollments().filter(e => e !== enrollment));
}
public emptyCart(): void {
this._enrollments.set([]);
}
}
我正在寻找更新 _enrollments 数组中特定注册中的数据的最佳方法。
我看到有两个选项:
是否有更好的方法来保持不变性并遵守关注点分离原则?
因为我们要更新数组中的元素
Cart
它应该属于Cart
类。
export class Enrollment {
private _productId = signal(0);
private _price = signal(0);
public productId = this._productId.asReadonly();
public price = this._price.asReadonly();
public setProductId(productId: number): void {
this._productId.set(productId);
}
public setPrice(price: number): void {
this._price.set(price);
}
}
export class Cart {
private _enrollments = signal<Enrollment[]>([]);
public enrollments = this._enrollments.asReadonly();
public addToCart(enrollment: Enrollment): void {
this._enrollments.set([...this._enrollments(), enrollment]);
}
public removeFromCart(enrollment: Enrollment): void {
this._enrollments.set(this._enrollments().filter((e) => e !== enrollment));
}
public emptyCart(): void {
this._enrollments.set([]);
}
public updateCartItem(productId: number, newPrice: number) {
const enrollments = this._enrollments();
const foundEnrollment: Enrollment | undefined = enrollments.find(
(item: any) => item.productId === productId
);
if (foundEnrollment) {
if (newPrice !== foundEnrollment.price()) {
foundEnrollment.setPrice(newPrice);
}
}
}
}