Skip to content

Instantly share code, notes, and snippets.

@goatslacker
Created May 30, 2015 04:35
Show Gist options
  • Save goatslacker/bdf5061f9b70a4fa4e99 to your computer and use it in GitHub Desktop.
Save goatslacker/bdf5061f9b70a4fa4e99 to your computer and use it in GitHub Desktop.
Shopping with alt and the new reducey stuff.
import Alt from './'
const alt = new Alt()
const ShopActions = alt.generateActions('addItem', 'taxPercentChanged')
const ItemStore = alt.createStore({
displayName: 'ItemStore',
state: {
items: []
},
bindListeners: {
addItem: ShopActions.addItem
},
addItem(item) {
this.setState({ items: this.state.items.concat(item) })
}
})
const TaxStore = alt.createStore({
displayName: 'TaxStore',
state: {
percentage: 0
},
bindListeners: {
taxPercent: ShopActions.taxPercentChanged
},
taxPercent(percentage) {
this.setState({ percentage })
}
})
const SubtotalStore = alt.createStore({
displayName: 'SubtotalStore',
state: {
subtotal: 0
},
reduce(alt, state, data) {
this.waitFor(ItemStore)
return {
subtotal: ItemStore.getState().items.reduce(
(total, item) => total + (item.price * item.quantity), 0
)
}
}
})
const TotalTaxStore = alt.createStore({
displayName: 'TotalTaxStore',
state: { totalTax: 0 },
reduce() {
this.waitFor(SubtotalStore, TaxStore)
return {
totalTax: SubtotalStore.getState().subtotal *
(TaxStore.getState().percentage / 100)
}
}
})
const TotalStore = alt.createStore({
displayName: 'TotalStore',
state: { total: 0 },
reduce() {
this.waitFor(SubtotalStore, TotalTaxStore)
return {
total: SubtotalStore.getState().subtotal + TotalTaxStore.getState().totalTax
}
}
})
function test() {
TotalStore.listen(state => console.log('Total price', state.total))
ShopActions.addItem({ name: 'Soap', price: 5, quantity: 2 })
ShopActions.taxPercentChanged(10)
}
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment