Question

In: Computer Science

Problem Description You have been asked to develop basic Event Broker functionality for a piece of...

Problem Description

You have been asked to develop basic Event Broker functionality for a piece of home automation software.

Your system needs to:

  • Subscribe event handlers to handle different types of events when they occur
  • Unsubscribe event handlers that no-longer need to handle specific events
  • Receive emitted events
  • Handle events by calling subscribed event handlers

Events & Handlers:

  • Each event has a type
  • Event handlers may subscribe to be handle events of a given type
  • An event handler can handle multiple types of event
  • An event can have multiple handlers
  • Handlers should be called in the order they were subscribed (FIFO)

Your Task

Your task is to plan and implement a JavaScript module for the system described above.

Your code will be run in a NodeJS environment as a module similar to this:

const bkr = require('./broker');

let handler1 = function() {    /* do stuff... */    }
let handler2 = function() {    /* do stuff... */    }

bkr.subscribe('event1',handler1);
bkr.subscribe('event1',handler2);
bkr.subscribe('event2',handler2);

bkr.emit('event1');
bkr.emit('event2');

bkr.unsubscribe('event1',handler1);

Your module needs to support 3 functions:

  • emit(type)
    • Takes a parameter event type, which is a string name of an event.
    • Runs all registered handlers of that event type in the order that those handlers were subscribed.
  • subscribe(type,handler)
    • Takes a parameter event type, which is a string name of an event.
    • Takes a parameter event handler, which is a function.
    • Whenever an event of this type is emitted, this handler function should run.
    • Multiple handlers may be added to an event
    • A handler may be added to multiple different events
    • A handler may only be added once to the same event
  • unsubscribe(type,handler)
    • Takes a parameter event type, which is a string name of an event.
    • Takes a parameter event handler, which is a function.
    • This event handler function should no longer be triggered when events of this type are emitted.

First, plan your system

  • Make sure you understand the problem.
  • Determine any data structures and algorithms that you might need.
  • Refer to the Notes/Readings listed in the section below for information on event brokers and JavaScript modules.

Finally, implement your code.

  • Create a file named broker.js and implement the emit(type), subscribe(type,handler), and unsubscribe(handler) functions and other code.
  • Be sure to thoroughly test your code.

Key Requirements

Be sure to adhere to the following requirements.
Not doing so may result in a reduction or complete loss of marks.

  • You must use JavaScript
  • You must not use any existing event handling/brokering functions/libraries

Solutions

Expert Solution

The custom library is created with which you can subscribe to events and emit the events. The library also supports unsubscribing from the event. The whole program is done in pure java script. No external libraries are used.

Broker.js


function Broker() {
        this.event = {};
}
// This method will register a handler for an event.
Broker.prototype.subscribe = function (eventName, handler) {
    // We will check if the event already exist in the event object, if so add to the array of handlers
        if(this.event[eventName])
        {
                const handlerArray=this.event[eventName];
                handlerArray.push(handler);
                this.event[eventName]=handlerArray;
        }
        else
        {
        // Create a new handler array and push the new handler to register it
                const handlerArray = [];
                handlerArray.push(handler);
                this.event[eventName]=handlerArray;
        }
        
}
// This method will deregister a handler for an event.
Broker.prototype.unsubscribe = function (eventName, handler) {
        if(this.event[eventName])
        {
        // We remove the handler from the event handler array
                const handlerArray=this.event[eventName];
                let handlerIndex = handlerArray.indexOf(handler);
                if(handlerIndex > -1)
                        handlerArray.splice(handlerIndex, 1);
                this.event[eventName]=handlerArray;
        }       
}
// This method will emit the event
Broker.prototype.emit = function (eventName) {
        handlerArray=this.event[eventName];
    // We iterate through each handlers in the array and invoke each of them
        for (let i = 0 ; i < handlerArray.length; i++)
        {
                handlerArray[i]();      
        }

}


module.exports = new Broker();

BrokerDriver.js

var bkr = require('./broker');

var handler1 =   function() { 
   console.log("handler1");  
}
var handler2 =  function() { 
   console.log("handler2");   
        }
console.log("Suscribing event1 with handler 1");
bkr.subscribe('event1',handler1);
console.log("Suscribing event1 with handler 2");
bkr.subscribe('event1',handler2);
console.log("Suscribing event2 with handler 2");
bkr.subscribe('event2',handler2);

console.log("Emitting event 1");
bkr.emit('event1');
console.log("Emitting event 2");
bkr.emit('event2');

console.log("Unsuscribing event1 with handler 1");
bkr.unsubscribe('event1',handler1);
console.log("Emitting event 1");
bkr.emit('event1');

Output


Related Solutions

You have been asked to develop an H&S orientation to provide employees with a basic level...
You have been asked to develop an H&S orientation to provide employees with a basic level of H&S training to demonstrate first steps towards a safety climate. What information do you want to cover off? What methods you will use to deliver this training? (15)
Suppose you have been asked to develop a simple model for the movement of ants in...
Suppose you have been asked to develop a simple model for the movement of ants in the presence of a food source. Discuss how you could simulate this model. Your answer should include any simplifying assumptions, some parameters that you’d need, and the interaction rules you would set up.
You have been asked to develop a care plan for a new client. How would you...
You have been asked to develop a care plan for a new client. How would you go about identifying the needs and preferences of clients and their family members prior to developing this care plan
Imagine you work for a health care organization and have been asked to develop a proposal...
Imagine you work for a health care organization and have been asked to develop a proposal on how the organization might adopt a technology trend to improve the quality of the health care delivered to organization members. Select and research two technology trends. Examples of technology trends: Telemedicine Optical imagery for diagnosing disease Electronic health records Telehealth Video translation services Dictation services (e.g., Dragon NaturallySpeaking) Medical equipment Health care robots Neural engineering Intelligent mobile devices National health care information network...
You work for a high-volume bakery and have been asked to develop a statistical model to...
You work for a high-volume bakery and have been asked to develop a statistical model to predict and assess the quality of the bread product as it relates to the time and temperature of the manufacturing (baking) process. You have collected time temperature experimental data shown in the attached “BreadExp” data file. You have also noted the weather on the days the bread was baked with a 0-1 indicator variable. (0= Cool and dry, 1= Warm and wet). The response...
1. You have been asked to develop a manual for your provider-employer. The manual is to...
1. You have been asked to develop a manual for your provider-employer. The manual is to detail a chemical hvgiene plan (CHP) for all employees in the office. How would you proceed? What should be included In the plan? In the CHP, include three major goals that will ensure the provider-employer's conmpliance with the hazard standard. 2. you have been asked to compile a manual of the SDSS for chemicals used in your workplace. What must be included in the...
As a statistical consultant, you have been asked to develop a linear model which shall be...
As a statistical consultant, you have been asked to develop a linear model which shall be given to first year executive MBA students. Variable           Name                                                   Description X1                   Gender                                                Male or Female X2                   GMAT Score                                      Score on GMAT Test X3                   College Degree Previously Earned     Bachelors, Masters, or PhD Y                     Income                                                            Annual Income in Thousand Dollars Where 1=Male and 2= Female for X1 and B = Bachelors Degree, M=Master’s Degree, and P= PhD for X3. Question Based on above information. Given...
1a. You have been asked to develop a pro forma statement of cash flow for an...
1a. You have been asked to develop a pro forma statement of cash flow for an office plaza. The information given to you is listed below: Property Information:                Age                                                                                        8 years                Rentable Space                                                                 300,000 sq.ft.                 # Stories                                                                              15                 # Tenants                                                                            40     Financial Information:                 Base Rent Avg.                                                                  $20 per sq.ft.                 Other Income/Parking                                                   $1.50 per sq.ft.                 Expenses Recoverable from Tenants                       $2.50 per sq.ft.                 Current Vacancy                                                               equals to 5% of...
Imagine you work for a health care organization and have been asked to develop a proposal...
Imagine you work for a health care organization and have been asked to develop a proposal on how the organization might adopt a technology trend to improve the quality of the health care delivered to organization members. Select and research two technology trends. Examples of technology trends: Telemedicine Optical imagery for diagnosing disease Electronic health records Telehealth Video translation services Dictation services (e.g., Dragon NaturallySpeaking) Medical equipment Health care robots Neural engineering Intelligent mobile devices National health care information network...
Imagine you work for a health care organization and have been asked to develop a proposal...
Imagine you work for a health care organization and have been asked to develop a proposal on how the organization might adopt a technology trend to improve the quality of the health care delivered to organization members. Examples of technology trends: Telemedicine Optical imagery for diagnosing disease Electronic health records Telehealth Video translation services Dictation services (e.g., Dragon NaturallySpeaking) Medical equipment Health care robots Neural engineering Intelligent mobile devices National health care information network A technology trend approved by your...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT