raix:eventddp

v0.0.1Published 9 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

raix:eventddp

This package adds events over ddp, so you can emit and listen to events from client and server.

1  var ddpEvents = new EventDDP('raix:push', Meteor.connection);
2
3  var ddpEvents.addListener('push', function(message) {
4    // Got message
5    // Use the notification api to display a nice native notification?
6    alert(message);
7  });
8
9  ddpEvents.setClient({
10    // Setting userId here throws an error
11    // userId: '',
12    // This is an example of metadata
13    appId: '2222',
14    foo: 'bar'
15  });
16
17  ddpEvents.emit('token', token);

On the server:

1  var ddpEvents = new EventDDP('raix:push');
2
3  // Added list of userId's - the selector is optional - if omitted then broadcast
4  ddpEvents.matchEmit('push', {
5    $and: [
6      userId: ['fsDFf7fsfdfs'],
7      appId: '2222',
8      foo: 'bar'
9    ]
10  }, 'Hello');
11
12  ddpEvents.addListener('token', function(client, token) {
13    if (client.userId) {
14        // check client.appId
15        // check client.foo
16    }
17  });

How does this work?

This is a simple walkthrough the core features:

Example:

1em = new EventDDP('test');
2
3if (Meteor.isClient) {
4  em.addListener('hello', function() {
5    console.log('SERVER HI', _.toArray(arguments));
6  }); 
7}
8
9if (Meteor.isServer) {
10  em.addListener('hello', function(/* client */) {
11    console.log('HELLO', _.toArray(arguments));
12  });
13}

Now emitting an event on the server or client will trigger the event listener eg.:

Browser console:

1  em.emit('hello');
2  // server --> HELLO [ { userId: null } ]

Notice that the first argument in the server listener is the client details.

We can set additional metadata on the client object if we want: (Browser console)

1  em.setClient({ foo: 'bar' });
2  em.emit('hello');
3  // server --> HELLO [ { foo: 'bar', userId: null } ]

Note userId is set by the server

We can also emit events from the server: ($ meteor shell)

1   em.emit('hello');
2   // client --> SERVER HI []

We can also use the matchEmit to do a client specific emit: ($ meteor shell)

1  // Match the client metadata
2  em.matchEmit('hello', { foo: 'bar' });
3  // client --> SERVER HI []

The matchEmit relies on the existing document matching in the MiniMongo package.

Example of how the matcher works, you might find it useful in other projects:

1  // $ meteor add minimongo
2  var match = new Minimongo.Matcher({ a: { $gt: 5 } });
3  match.documentMatches({ a: 1 }); // { result: false }
4  match.documentMatches({ a: 6 }); // { result: true }

TODO:

  • Write the full api
  • Write complete test coverage

Kind regards Morten