ReQL command: EventEmitter (cursor)
Command syntax
cursor.addListener(event, listener) cursor.on(event, listener) cursor.once(event, listener) cursor.removeListener(event, listener) cursor.removeAllListeners([event]) cursor.setMaxListeners(n) cursor.listeners(event) cursor.emit(event, [arg1], [arg2], [...])
Description
Cursors and feeds implement the same interface as Node’s EventEmitter.
- Two events can be emitted,
dataanderror. - Once you start using the
EventEmitterinterface, the other RethinkDB cursor commands likenext,toArray, andeachwill not be available anymore. - The first time you call an
EventEmittermethod, the cursor or feed will emit data just after the I/O events callbacks and beforesetTimeoutandsetIntervalcallbacks.
Example: Broadcast all messages with socket.io.
r.table("messages").orderBy({index: "date"}).run(conn, function(err, cursor) {
if (err) {
// Handle error
return
}
cursor.on("error", function(error) {
// Handle error
})
cursor.on("data", function(message) {
socket.broadcast.emit("message", message)
})
});
This query can be rewritten with the each command:
r.table("messages").orderBy({index: "date"}).run(conn, function(err, cursor) {
if (err) {
// Handle error
return
}
cursor.each(function(error, message) {
if(error) {
// Handle error
}
socket.broadcast.emit("message", message)
})
});
Example: Broadcast all the messages inserted.
r.table("messages").changes().filter({old_val: null}).run(conn, function(err, feed) {
if (err) {
// Handle error
return
}
feed.on("error", function(error) {
// Handle error
})
feed.on("data", function(newMessage) {
socket.broadcast.emit("message", newMessage)
})
});
© RethinkDB contributors
Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
https://rethinkdb.com/api/javascript/ee-cursor/