.. _client-usage:

Usage
=====

Connection
----------

A connection can simply be created using the ``Omnibus`` constructor. To open
an instance provide as the constructors parameters:

* ``transport``, it describes the implementation of the web socket transport medium. This can be the browser's default implementation ``WebSocket`` or alternatively ``SockJS``.
* ``endpoint``, is the location where the remote listens.
* ``options``, can optionally specify the behaviour of the connection.

.. code-block:: javascript

    var transport = WebSocket;
    var endpoint = 'ws://localhost:4242/ec';
    var connection = new Omnibus(transport, endpoint);

Options
```````

In the code above are no options provided, so the instance use their default options.
To take a look at the default options you can access the ``Omnibus.defaults`` property.
The following options can be provided as property:

* ``authToken``, a string which identifies a client connection. The string will be generated by the remote.
* ``ignoreSender``, a boolean (default ``true``) defines if you send a message through a channel and the remote just forwards the message to their receivers, it ignores your own message and doesn't triggers any action.
* ``autoReconnect``, a boolean (default ``true``) enables an auto-reconnect when the connection to the remote gets lost unexpectedly.
* ``autoReconnectTimeout``, a number (default ``500``) is only used when ``autoReconnect`` option is enabled. It describes the timeout in milliseconds when the next try to connect to the remote will be performed.

.. code-block:: javascript

    var transport = WebSocket;
    var endpoint = 'ws://localhost:4242/ec';
    var options = {
        ignoreSender: true,
        autoReconnect: true,
        autoReconnectTimeout: 1000
    };
    var connection = new Omnibus(transport, endpoint, options);

Public functions
````````````````

* ``getId``, returns the unique identifier of this connection which is used to communicate with the remote.
* ``isAuthenticated()``, returns whether the connection was authenticated at the remote.
* ``isConnected()``, returns if the connection is established.
* ``openChannel(name)``, returns a channel with the given name. When a channel with the same name was opend previously, then it returns the same channel instance as before. Otherwise it instantiates a new channel with the given name. When a previously returned channel instance is already closed, a new instance will be generated. For more information about a channel instance take a look into the channel_ section.
* ``getChannel(name)``, returns a channel instance which was opend previously through this connection. If there was not opened a channel with the given name before the function returns 'undefined'.
* ``closeChannel(instanceOrName)``, closes and finally destroys a channel which was opened through this connenction.

The connection has some more public functions. Some of them are not intended
to be used directly. The others are to be used with the omibus eventbus. The
connection fires some predefined events. For more details according events see
the events_ section below.

Channel
-------

On an open connection its easy to open a channel. The channel must exist at the
remote. For example you would like to send or receive messages from the
channel *foo*, the subscription would look like this:

.. code-block:: javascript

    var foo = connection.openChannel('foo');

To send a message through this channel you call:

.. code-block:: javascript

    // send message with type 'bar' through channel:
    foo.send('bar');

    // send mesage with type 'baz' and data through channel:
    foo.send('baz', {
        omg: 'wtf'
    });

To receive messages from the remote through an open channel add an eventhandler
to handle the message and perform actions:

.. code-block:: javascript

    foo.on('bar', function(event) {
        // perform some custom action here...
    });

The channel fires some predefined events. For more details according events see
the events_ section below.

To close a channel instance call the ``close()`` function. This triggers an
unsubscription from the connection. Finally it closes the channel from the
remote and calls ``destroy()`` indirectly.

The ``destroy()`` function is not meant to be called directly. This will be
called through the instance or the referred connection. When called all
registered events_ will be removed from the called instance.

Events
------

The *django-omnibus* ships his own eventbus system. The connection_ and channel_
classes inherit from the eventbus.
There are some functions to interact with the eventbus sytem:

* ``on(eventName, eventHandler)``, registers an eventHandler to a particular eventName. This function is chainable to call multiple functions on an instance of the eventbus. To handle all events triggered through an eventbus instance by a single eventHandler use the value ``'*'`` as wildcard eventName.
* ``off(eventName, eventHandler)``, removes registered eventHandler(s) from the eventbus instance. This function is chainable to call multiple functions on an instance of the eventbus. When called without any parameters all registered eventHandlers are removed. When called with eventName parameter all registered eventHandlers according this particular eventName are removed. When called with eventName and a reference to an eventHandler function this given handler for the particular eventName will be removed.
* ``trigger(eventName, eventData)``, triggers all registered eventHandlers on a particular eventName. EventData can be send through each call to each handler. This function is chainable to call multiple functions on an instance of the eventbus. All eventHandlers registered with the wildcard eventName ``'*'`` will be triggered as well.

All predefined event types are listet through the ``Omnibus.events`` property.
The containing constants are prefixed with ``CONNECTION`` or ``CHANNEL`` to
specifiy the instance who will fire this event.

* ``Omnibus.events.CHANNEL_SUBSCRIBED``, notifies about a channel subscription state.
* ``Omnibus.events.CHANNEL_UNSUBSCRIBED``, notifies about the current channel unsubscription state.
* ``Omnibus.events.CHANNEL_CLOSE``. notifies that the channel instance will be closed.
* ``Omnibus.events.CHANNEL_DESTROY``, notifies that the channel instance will be destroyed and isn't available for further usage.
* ``Omnibus.events.CONNECTION_CONNECTED``, notifies about an established connenction.
* ``Omnibus.events.CONNECTION_DISCONNECTED``, notifies about a (may be accidentally) closed connection.
* ``Omnibus.events.CONNECTION_AUTHENTICATED``, notifies about a successful identification.
* ``Omnibus.events.CONNECTION_ERROR``, notifies about an occurred error through the websocket implementation.

An example usage looks like this:

.. code-block:: javascript

    var transport = WebSocket;
    var endpoint = 'ws://localhost:4242/ec';
    var connection = new Omnibus(transport, endpoint);

    connection
        .on(Omnibus.events.CHANNEL_SUBSCRIBED, function(event) {
            // handle subscription actions here...
        })
        .on(Omnibus.events.CONNECTION_AUTHENTICATED, function(event) {
            // handle authentication actions here...
        });
