Last active
May 22, 2019 17:20
-
-
Save seysdev/5ae856f0d7967bdcb62260cf4c973402 to your computer and use it in GitHub Desktop.
not reactive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Without reactive paradigm | |
| */ | |
| class Car { | |
| constructor(sales) { | |
| this.items = []; | |
| this.sales = sales; | |
| } | |
| add(item) { | |
| this.items.push(item); | |
| } | |
| checkout() { | |
| const total = this.items.reduce( | |
| (vant, vact) => vant + vact.price, 0 | |
| ); | |
| this.sales.update(total.toFixed(3)); | |
| } | |
| } | |
| class Sales { | |
| constructor() { | |
| this.total = 0; | |
| } | |
| update(total) { | |
| this.total = total; | |
| } | |
| } | |
| const sales = new Sales(); | |
| const car = new Car(sales); | |
| car.add({ name: 'Ford', price: 14.200 }); | |
| car.add({ name: 'Toyota', price: 10.000 }); | |
| car.checkout(); | |
| console.log('sales',sales.total); // 24.200 | |
| /* | |
| * With reactive paradigm | |
| */ | |
| import { Subject } from 'rxjs'; | |
| class Car { | |
| constructor() { | |
| this.items = []; | |
| this.total = []; | |
| this.cObs = new Subject() | |
| } | |
| add(item) { | |
| this.items.push(item); | |
| } | |
| checkout() { | |
| const total = this.items.reduce( | |
| (vant, vact) => vant + vact.price, 0 | |
| ); | |
| this.cObs.next(total) | |
| } | |
| } | |
| class Sales { | |
| constructor(car) { | |
| this.total = 0; | |
| car.cObs.subscribe(this.update.bind(this)) | |
| } | |
| update(total) { | |
| this.total = total; | |
| } | |
| } | |
| const car = new Car(); | |
| const sales = new Sales(car); | |
| car.add({ name: 'Ford', price: 14.200 }); | |
| car.add({ name: 'Toyota', price: 10.000 }); | |
| car.checkout(); | |
| console.log('sales', sales.total); // 24.200 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment