Moleculer: help me about create an event listener

Created on 9 May 2019  路  1Comment  路  Source: moleculerjs/moleculer

please tell me how i can add event listener to my service and always when hello action called that event log something . I try to read the documentation but it's not enough.

"use strict";

module.exports = {
    name: "greeter",
    /**
     * Service settings
     */
    settings: {

  },

    /**
     * Service dependencies
     */
    dependencies: [],   

    /**
     * Actions
     */
    actions: {

        /**
         * Say a 'Hello'
         *
         * @returns
         */
        hello() {
            return "Hello Moleculer";
        },

    },

    /**
     * Events
     */
    events: {

    },

    /**
     * Methods
     */
    methods: {

    },

    /**
     * Service created lifecycle event handler
     */
    created() {

    },

    /**
     * Service started lifecycle event handler
     */
    started() {

    },

    /**
     * Service stopped lifecycle event handler
     */
    stopped() {

    }
};

Most helpful comment

@zoheirkhonyagar here is the code.
Please don't use Git Issues for questions. Consider using the chat https://gitter.im/moleculerjs/moleculer

"use strict";

module.exports = {
  name: "greeter",

  actions: {
    hello() {
      this.logger.info("Preparing to Emit");
      const randomNum = Math.random();
      // Emit an actual Event
      this.broker.emit("greeter.MyCustomEvent", { num: randomNum });
      this.logger.info("Emitted");

      return "Hello Moleculer";
    }
  },

  events: {
    // Event Listener
    "greeter.MyCustomEvent"(payload) {
      this.logger.info("Event Caught");
      this.logger.info(payload);
    }
  }
};

Result:
mol

>All comments

@zoheirkhonyagar here is the code.
Please don't use Git Issues for questions. Consider using the chat https://gitter.im/moleculerjs/moleculer

"use strict";

module.exports = {
  name: "greeter",

  actions: {
    hello() {
      this.logger.info("Preparing to Emit");
      const randomNum = Math.random();
      // Emit an actual Event
      this.broker.emit("greeter.MyCustomEvent", { num: randomNum });
      this.logger.info("Emitted");

      return "Hello Moleculer";
    }
  },

  events: {
    // Event Listener
    "greeter.MyCustomEvent"(payload) {
      this.logger.info("Event Caught");
      this.logger.info(payload);
    }
  }
};

Result:
mol

Was this page helpful?
0 / 5 - 0 ratings

Related issues

abdavid picture abdavid  路  4Comments

Kamil93 picture Kamil93  路  3Comments

demetriusnunes picture demetriusnunes  路  5Comments

ngraef picture ngraef  路  4Comments

slinkardbrandon picture slinkardbrandon  路  4Comments