Skip to content

Commit

Permalink
fix(events): trigger events before methods resolve #54
Browse files Browse the repository at this point in the history
  • Loading branch information
gr2m committed Jul 24, 2015
1 parent 41fa79e commit 1b225d1
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 36 deletions.
36 changes: 36 additions & 0 deletions helpers/eventify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
module.exports = eventify

/**
* runs a method from the API and triggers events on each object.
*
* Note that we didn't implement this pased on PouchDB's .changes()
* API on purpose, because of the timeing the events would get triggered.
* See https://github.com/hoodiehq/pouchdb-hoodie-api/issues/54
**/
function eventify (db, state, method) {
return function () {
return method.apply(db, arguments).then(function (result) {
console.log('result')
console.log(result)
if (Array.isArray(result)) {
result.forEach(triggerEvent.bind(null, state))
} else {
triggerEvent(state, result)
}

return result
})
}
}

function triggerEvent (state, object) {
var eventName = 'add'
if (object._deleted) {
eventName = 'remove'
} else if (parseInt(object._rev, 10) > 1) {
eventName = 'update'
}

state.emitter.emit(eventName, object)
state.emitter.emit('change', eventName, object)
}
26 changes: 0 additions & 26 deletions helpers/start-listen-to-changes.js

This file was deleted.

19 changes: 9 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,25 @@
var exports = module.exports = { hoodieApi: hoodieApi }

var EventEmitter = require('events').EventEmitter
var startListenToChanges = require('./helpers/start-listen-to-changes')

var eventify = require('./helpers/eventify')

function hoodieApi (options) {
var state = {
emitter: options && options.emitter || new EventEmitter()
}

state.emitter.once('newListener', startListenToChanges.bind(this, state))

return {
db: this,
add: require('./add').bind(this),
add: eventify(this, state, require('./add')),
find: require('./find').bind(this),
findAll: require('./find-all').bind(this),
findOrAdd: require('./find-or-add').bind(this),
update: require('./update').bind(this),
updateOrAdd: require('./update-or-add').bind(this),
updateAll: require('./update-all').bind(this),
remove: require('./remove').bind(this),
removeAll: require('./remove-all').bind(this),
findOrAdd: eventify(this, state, require('./find-or-add')),
update: eventify(this, state, require('./update')),
updateOrAdd: eventify(this, state, require('./update-or-add')),
updateAll: eventify(this, state, require('./update-all')),
remove: eventify(this, state, require('./remove')),
removeAll: eventify(this, state, require('./remove-all')),
on: require('./lib/on').bind(this, state),
one: require('./lib/one').bind(this, state),
off: require('./lib/off').bind(this, state),
Expand Down

0 comments on commit 1b225d1

Please sign in to comment.