W3cubDocs

/RethinkDB JavaScript

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, data and error.
  • Once you start using the EventEmitter interface, the other RethinkDB cursor commands like next, toArray, and each will not be available anymore.
  • The first time you call an EventEmitter method, the cursor or feed will emit data just after the I/O events callbacks and before setTimeout and setInterval callbacks.

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)
    })
});

Related commands

Get more help

Couldn't find what you were looking for?

© RethinkDB contributors
Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
https://rethinkdb.com/api/javascript/ee-cursor/