Skip to content

Commit

Permalink
Allow listening to same action with multiple methods
Browse files Browse the repository at this point in the history
  • Loading branch information
goatslacker committed Aug 28, 2015
1 parent b2c0b31 commit a57d062
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 8 deletions.
25 changes: 18 additions & 7 deletions src/alt/store/AltStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,25 +48,36 @@ class AltStore {
state: this.state
})

const actionHandler = model.actionListeners[payload.action] ||
model.otherwise
const actionHandlers = model.actionListeners[payload.action]

if (actionHandler) {
const result = handleDispatch(() => {
return actionHandler.call(model, payload.data, payload.action)
}, payload)
if (actionHandlers || model.otherwise) {
let result

if (actionHandlers) {
result = handleDispatch(() => {
return actionHandlers.filter(Boolean).every((handler) => {
return handler.call(model, payload.data, payload.action) !== false
})
}, payload)
} else {
result = handleDispatch(() => {
return model.otherwise(payload.data, payload.action)
}, payload)
}

if (result !== false && !this.preventDefault) this.emitChange()
}



if (model.reduce) {
handleDispatch(() => {
this.state = model.reduce(this.state, payload)
}, payload)

if (!this.preventDefault) this.emitChange()
}


this.lifecycle('afterEach', {
payload,
state: this.state
Expand Down
3 changes: 2 additions & 1 deletion src/alt/store/StoreMixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ const StoreMixin = {

// You can pass in the constant or the function itself
const key = symbol.id ? symbol.id : symbol
this.actionListeners[key] = handler.bind(this)
this.actionListeners[key] = this.actionListeners[key] || []
this.actionListeners[key].push(handler.bind(this))
this.boundListeners.push(key)
},

Expand Down
29 changes: 29 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,35 @@ const tests = {
myStore.listen(null)
}, TypeError, 'listen expects a function')
},

'lots of listens'() {
const ImportKeysActions = alt.generateActions('change', 'saved')

const call = sinon.spy()

const BalanceClaimStore = alt.createStore(class {
constructor() {
this.bindListeners({
onRefreshBalanceClaims: ImportKeysActions.saved,
onLoadMyAccounts: [
ImportKeysActions.change, ImportKeysActions.saved
]
})
}

onRefreshBalanceClaims() {
call()
}

onLoadMyAccounts() {
call()
}
})

ImportKeysActions.saved()

assert(call.calledTwice, 'multiple action handlers are ok')
},
}

export default tests

0 comments on commit a57d062

Please sign in to comment.