[rank_math_breadcrumb]

How to use Event Aggregator in Aurelia

In a frontend Application we sometimes need to send some message or notify other components to update UI based on some data. We can achieve this using Event Aggregator in Aurelia. I will try to show you how it works. We need to use Dependency Injection here. This is a way to create a singleton object instance of a class (service methods or utils) in constructor and use it inside that class.

To simply demonstrate Event Aggregator I am creating 2 components (Custom Elements) Message and Form. Message is just display a message property and Form component has one text area and a button. We want to pass whatever user enters in the textbox when user clicks on the button. See how the codes will look like for these 2 components.

Message.js

 

import { inject } from "aurelia-framework";
import { EventAggregator } from "aurelia-event-aggregator";

@inject(EventAggregator)
export class Message {
  message = "Default Text";

  constructor(eventAggregator) {
    this.eventAggregator = eventAggregator;
    this.eventAggregator.subscribe("UpdateMessage", (payload) => {
      this.message = payload;
    });
  }
}

Message.html

<template>
  <div>
    ${message}
  </div>
</template>

To use dependency injector we need to use inject annotation which is from aurelia-framework. We need to tell in the inject method which classes we will use to initialize. Those class instances will be passed in the constructor. We are using EventAggregator from aurelia-event-aggregator.In eventAggregator object we have subscribe method which takes 2 parameters 1st one is channel name as string (I used “UpdateMessage”) and 2nd one is a function. If it publishes any messages in the same channel this function will be called.

Form.js

import { inject } from "aurelia-framework";
import { EventAggregator } from "aurelia-event-aggregator";

@inject(EventAggregator)
export class Form {
  message = "";

  constructor(eventAggregator) {
    this.eventAggregator = eventAggregator;
  }
  send = () => {
    this.eventAggregator.publish("UpdateMessage", this.message);
  };
}

Form.html

<template>
  <div>
    <input value.bind="message"/>
    <button click.delegate="send()">Send</button>
  </div>
</template>

Here we publish the message property of Form class to the UpdateMessage channel. publish method takes 1st parameter for Channel Name and 2nd parameter is for payload data which will be passed to the function of subscribe method.

Sometimes we need to refresh some components data based on some user actions. That’s how  components can communicate with each other.

By Vivasoft Team
By Vivasoft Team
Hire Exceptional Developers Quickly

Find Your Talent

Share this blog on

Hire a Talented Developer from Vivasoft

Lets discuss about your offshore project. We can Help you by our skillful Global team. You can take a free counciling by taking a schedule

Related Post