cloudhead/cradle — Issue #134: How to use changes API?
Author: pexd
Created: 2012-01-17 13:39:45+00:00
State: open

Hi,

I just went through the readme and all examples work, except for the changes API.

What I would like to do:
- is to execute code, whenever (the result of) a view changes (without polling),
- not keep track of sequence numbers,
- get a reference (or something similar) to the changed/updated/added elements.

So basically:
View A results change --> call method A
View B results change --> call method B
etc.

How can I implement this in Cradle? Is it possible? (I guess there has to be a way to register a call-back function.)

I tried the examples in the readme on the star wars data:

```javascript
db.changes(function(list) {
list.forEach(function(change) {console.log(change);});
});
```

results in:

```text
pha@Ubuntu-1110-oneiric-64-minimal:~/code/dbtest$ node helloworld.js
/home/phantom/code/dbtest/helloworld.js:67
list.forEach(function(change) {console.log(change);});
^
TypeError: Cannot call method 'forEach' of null
...
```

next try:

```javascript
db.changes({since: 1}, function(list){
list.forEach(function(change) {console.log(change);});
});
```

results in:

```text
pha@Ubuntu-1110-oneiric-64-minimal:~/code/dbtest$ node helloworld.js
/home/phantom/code/dbtest/helloworld.js:71
list.forEach(function(change) {console.log(change);});
^
TypeError: Cannot call method 'forEach' of null
...
```

next try:

```javascript
db.changes({ since: 6}).on('response', function(res) {
res.on('data', function(change) {
console.log("-- data: " + change.force);
});
res.on('end', function() { console.log("-- end ");});
});
```

results in:

```text
pha@Ubuntu-1110-oneiric-64-minimal:~/code/dbtest$ node helloworld.js
-- data: undefined
-- data: undefined
-- data: undefined
undefined:0
^
SyntaxError: Unexpected end of input
....
```

The problem that I also see, is that the execution of the js file terminates. I thought about testing the functionality, by adding or changing data in Futon. But, of course, this is not possible, since the execution of the js terminates before I can make any changes manually. To make use of callbacks, a script/server would have to run permanently.

Can anybody help? Thanks in advance!