Skip to main content
Version: 3.x.x

Socket Emitter


Introduction

Emitter is a class that creates a template for sending events and stores all the necessary information needed for their creation. Its strength is its strict and predictable data structure.

You can trigger a event with the emit method, which send data to sever.


Purpose

  • Configures events templates
  • Standardizes the system’s data schema
  • Sends events to server

Initialization

Emitter should be initialized from the Socket instance with createEmitter method. This passes a shared reference to the place that manages communication in the application.

import { socketInstance } from "./socket";

export const sendChatMessage = socketInstance.createEmitter<ChatMessageType, AcknowledgementResponseType>()({
name: "chat-message", // name of the event
});

export const sendUserStatus = socketInstance.createEmitter<UserStatusType, AcknowledgementResponseType>()({
name: "status", // name of the event
});

Usage

Request Data

Use the setData method to instruct any data to be sent to the server.

sendChatMessage.setData({ message: "message" });

Emitting

Use the emit method to start the event emitting.

sendChatMessage.emit({ message: "message" });

// or

sendChatMessage.setData({ message: "message" }).emit();

Acknowledgements

Use the acknowledgements by passing the second parameter to the emitting method.

caution

Make sure your server is supporting the acknowledgements! When using default adapter, make sure you pass the id of the event in returning event, when using custom adapters, you have to implement according to it's specification.

sendChatMessage.emit({ data: { messsage: "some message" } }, (error, data) => {
if (error) {
alert("No server response!");
} else {
alert("Message received on server.");
}
});

Methods

Using methods on a emitter is different from other classes in Hyper Fetch. This is to ensure isolation between different uses, which allows you to avoid overwriting previously-prepared emitters and to dynamically generate keys for queues or the cache.

danger

Using any method on emitter returns its clone! We don't return a reference!

// ❌ WRONG

const emitter = sendMessageEmitter;

emitter.setData({ message: "some message" }); // Returns CLONED emitter with assigned data

emitter.emit(); // Server error - no data
// ✅ Good

const emitter = sendMessageEmitter;

const emitterWithData = emitter.setData({ message: "some message" }); // Returns CLONED emitter with assigned data

emitterWithData.emit(); // Success

Parameters

Configuration options

{
name: string;
options: AdditionalEmitterOptions;
timeout: number;
}