API v 1.0
JavaScript

Channels

The Channel object exposes the following public properties:

The current ChannelState of this Channel. See the supported channel states for more information.

When a channel failure occurs this attribute is populated.

The type is ErrorInfo.

The name String unique to this channel.

Provides access to the Presence object for this channel which can be used to access members present on the channel, or participate in presence.

There are two overloaded versions of this method:

publish(String name, Object data, callback(ErrorInfo err))

Publish a single message on this channel based on a given event name and payload. A callback may optionally be passed in to this call to be notified of success or failure of the operation. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling publish will implicitly attach the channel.

publish(Object[] messages, callback(ErrorInfo err))

Publish several messages on this channel. A callback may optionally be passed in to this call to be notified of success or failure of the operation. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling publish will implicitly attach the channel.

Parameters

name
event name for the published messageType: String
data
data payload for the message. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.Type: Object
messages
An array of message objects to publishType: Message []
callback
is a function of the form function(err) which is called upon completion

There are overloaded versions of this method:

subscribe(listener(Message))

Subscribe to messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.

subscribe(String name, listener(Message))

Subscribe to messages with a given event name on this channel. The caller supplies a listener function, which is called each time one or more matching messages arrives on the channel.

subscribe(String[] names, listener(Message))

Subscribe a single listener to messages on this channel for multiple event name values.

Parameters

name
The event name to subscribe toType: String
names
An array of event names to subscribe toType: String[]
listener
is a function of the form function(message) to be called for each message

Considerations

  • If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling subscribe will implicitly attach the channel. However, regardless of the implicit attach outcome, the listener will still be registered
  • If subscribe is called more than once with the same listener, then duplicates will be registered. For example, if you subscribe twice with the same listener and a message is later received, the same listener will be invoked twice
  • The registered listener remains active on the channel regardless of the current channel state. For example, if you call subscribe when a channel is attached and it later becomes detached or even failed, when the channel is reattached and a message is received, the listeners originally registered will still be invoked. Listeners are only removed when calling unsubscribe or when a channel is released using the Realtime.channels.release(name) method

There are three overloaded versions of this method:

unsubscribe(String name, listener)

Unsubscribe the given listener for the specified event name. This removes an earlier event-specific subscription.

unsubscribe(listener)

Unsubscribe the given listener (for any/all event names). This removes an earlier subscription.

unsubscribe()

Unsubscribes all listeners to messages on this channel. This removes all earlier subscriptions.

Parameters

name
The event name to unsubscribe fromType: String
names
An array of event names to unsubscribe fromType: String[]
listener
is the callback listener function that was previously subscribed

history(Object options, callback(ErrorInfo err, PaginatedResult<Message> resultPage))

Gets a paginated set of historical messages for this channel. If the channel is configured to persist messages to disk, then message history will typically be available for 24 – 72 hours. If not, messages are only retained in memory by the Ably service for two minutes.

Parameters

options
an optional object containing the query parameters, as specified in the message history API documentationType: Object
callback
is a function of the form: function(err, resultPage)

Further details of the supported options params, see message history API documentation.

attach(callback(ErrorInfo err))

Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel will be received by any channel listeners registered using subscribe(). Any resulting channel state change will be emitted to any listeners registered using the on or once methods.

As a convenience, attach() will be called implicitly if either publish() or subscribe() for the Channel is called, or enter() or subscribe() is called on the Presence for this Channel.

Parameters

callback
is a function of the form function(err) and is called once the channel attach succeeds or fails

detach(callback(ErrorInfo err))

Detach from this channel. Any resulting channel state change will be emitted to any listeners registered using the on or once methods.

Please note: Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.

Parameters

callback
is a function of the form function(err) and is called once the channel detach succeeds or fails

There are two overloaded versions of this method:

on(String event, listener(ChannelStateChange stateChange))

Register the given listener for the specified ChannelEvent on the Channel.

The listener is passed a ChannelStateChange object that contains the current state, previous state, a boolean indicating whether the channel was resumed, and an optional reason for the state change.

on(listener(ChannelStateChange stateChange))

Register the given listener for all ChannelEvents on the Channel.

The listener is passed a ChannelStateChange object that contains the current state, previous state, the event, a boolean indicating whether the channel was resumed, and an optional reason for the state change.

Parameters

event(s)
the channel event(s) to subscribe to, see ChannelEvent for supported channel eventsType: String or String[]
listener
is a function of the form function(stateChange) to be notified for matching event changes.

Example

Browser ChannelState change example

There are two overloaded versions of this method:

once(String event, listener(ChannelStateChange stateChange))

Register the given listener for a single occurrence of the specified ChannelEvent on the Channel. Once the listener has been called, it is removed as a registered listener and will not be called again.

The listener is passed a ChannelStateChange object that contains the current state, previous state, the event, a boolean indicating whether the channel was resumed, and an optional reason for the event change.

once(listener(ChannelStateChange stateChange))

Register the given listener for a single occurrence of any ChannelEvent on the Channel. Once the listener has been called, it is removed as a registered listener and will not be called again.

The listener is passed a ChannelStateChange object that contains the current state, previous state, the event, a boolean indicating whether the channel was resumed, and an optional reason for the event change.

Parameters

event
the channel event to subscribe to, see ChannelEvent for supported channel eventsType: String
listener
is a function of the form function() to be notified for a single occurrence of a matching event change. The current event is available as this.event

There are two overloaded versions of this method:

off(String event, listener)

Remove the given listener for the ChannelEvent .

off(listener)

Remove the given listener for all ChannelEvents.

Parameters

event(s)
the channel event(s) to unsubscribe fromType: String or String[]
listener
is the listener function to be removed

A ChannelStateChange is a type encapsulating state change information emitted by the Channel object. See Channel#on to register a listener for one or more events.

Attributes

current
the new current stateType: ChannelState
previous
the previous state. (for the update event, this will be equal to the current state)Type: ChannelState
event
the event that triggered this state changeType: ChannelEvent
reason
an ErrorInfo containing any information relating to the transitionType: ErrorInfo
resumed
a boolean indicated whether message continuity on this channel is preserved, see Nonfatal channel errors for more info.Type: Boolean

A Message represents an individual message that is sent to or received from Ably.

Properties

name
Event name, if providedType: String
data
The presence update payload, if providedType:
extras
Metadata and/or ancillary payloads, if provided. The only currently valid payload for extras is the push object.Type:
id
Unique ID assigned by Ably to this message. Can optionally be assigned by the client as part of idempotent publishingType: String
clientId
The client ID of the publisher of this messageType: String
connectionId
The connection ID of the publisher of this messageType: String
timestamp
Timestamp when the message was received by the Ably service, as milliseconds since the epochType: Integer
encoding
This will typically be empty as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payloadType: String

Message.fromEncoded(Object encodedMsg, ChannelOptions channelOptions?) → Message

A static factory method to create a Message from a deserialized Message-like object encoded using Ably’s wire protocol.

Parameters

encodedMsg
a Message-like deserialized object.Type: Object
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.Type: Object

Returns

A Message object

Message.fromEncodedArray(Object[] encodedMsgs, ChannelOptions channelOptions?) → Message[]

A static factory method to create an array of Messages from an array of deserialized Message-like object encoded using Ably’s wire protocol.

Parameters

encodedMsgs
an array of Message-like deserialized objects.Type: Array
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.Type: Object

Returns

An Array of Message objects

Channel options are used for configuring encryption.

Properties

Requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See an exampleType: CipherParams

A PaginatedResult is a type that represents a page of results for all message and presence history, stats and REST presence requests. The response from a Ably REST API paginated query is accompanied by metadata that indicates the relative queries available to the PaginatedResult object.

Properties

items
contains the current page of results (for example an Array of Message or PresenceMessage objects for a channel history request)Type: Array <Message, Presence, Stats>

Methods

first(callback(ErrorInfo err, PaginatedResult resultPage))

Returns a new PaginatedResult for the first page of results.

Boolean hasNext()

Returns true if there are more pages available by calling next and returns false if this page is the last page available.

Boolean isLast()

Returns true if this page is the last page and returns false if there are more pages available by calling next available.

next(callback(ErrorInfo err, PaginatedResult resultPage))

Returns a new PaginatedResult loaded with the next page of results. If there are no further pages, then null is returned.

JavaScript
channel.history(function(err, paginatedResult) { console.log('Page 0 item 0:' + paginatedResult.items[0].data); paginatedResult.next(function(err, nextPage) { console.log('Page 1 item 1: ' + nextPage.items[1].data); console.log('Last page?: ' + nextPage.isLast()); }); });
Copied!