Skip to content

Commit

Permalink
refactor(with-id-prefix): move event handling in a new file
Browse files Browse the repository at this point in the history
  • Loading branch information
Terreii committed Jul 14, 2018
1 parent 5beae55 commit fb9dbb6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
12 changes: 12 additions & 0 deletions lib/helpers/prefix-event-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 1,12 @@
module.exports = prefixEventHandler

function prefixEventHandler (prefix, prefixState) {
prefixState.parentEmitter.on('change', function (eventName, object) {
if (object._id.substr(0, prefix.length) !== prefix) {
return
}

prefixState.emitter.emit('change', eventName, object)
prefixState.emitter.emit(eventName, object)
})
}
16 changes: 7 additions & 9 deletions lib/with-id-prefix.js
Original file line number Diff line number Diff line change
@@ -1,6 1,7 @@
module.exports = withIdPrefix

var EventEmitter = require('events').EventEmitter
var prefixEventHandler = require('./helpers/prefix-event-handler')

/**
* returns API with all CRUD methods scoped to id prefix
Expand All @@ -26,20 27,17 @@ function withIdPrefix (state, prefix) {
}
}

var prefixState = {api: api, emitter: emitter}
var prefixState = {
api: api,
parentEmitter: state.emitter,
emitter: emitter
}

api.on = require('./on').bind(null, prefixState)
api.one = require('./one').bind(null, prefixState)
api.off = require('./off').bind(null, prefixState)

state.emitter.on('change', function (eventName, object) {
if (object._id.substr(0, prefix.length) !== prefix) {
return
}

emitter.emit('change', eventName, object)
emitter.emit(eventName, object)
})
prefixEventHandler(prefix, prefixState)

return api
}

0 comments on commit fb9dbb6

Please sign in to comment.