Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Creating an event-driven class/module
    I'm trying to create a class/module that will easily allow me to create a *thing*. I have one public function, `makeSomething`, and multiple private functions (that are nested inside a parent `_process`). I'm using `EventEmitters` - very similar to JavaScript's `addEventListener`. **The issue:** my `that.on(...)` lines (lines 26-29) are not being run because `_process` has not been called. I can't pull those lines out of the `_process` function either because the members of `_process` (`_sanitize`, `_validate`, etc.) can only be called from within. This is my first time making a class/module like this. Am I doing something wrong? Is there a better way of making an event-based class/module? I know that if I didn't nest any functions like I did with `_sanitize` and `_validate`, then my code would work just fine but I feel like adding in layers is a part of writing clean code. I'm really just looking for guidance on this.
    var MyThing = function() {
        var that = this;
    
        this.makeSomething = function() {
            that.emit("blogRequest");
        };
    
        var _process = function() {
            var _sanitize = function() {
                that.emit("sanitized");
            };
    
            var _validate = function() {
                that.emit("validated");
            };
    
            var _encrypt = function() {
                that.emit("hashCreated");
            };
    
            var _success = function() {
                that.emit("infoProcessed");
            };
    
            that.on("blogRequest", _sanitize);
            that.on("sanitized", _validate);
            that.on("validated", _encrypt);
            that.on("hashCreated", _success);
        };
    };
    
    var myThing = new MyThing();
    myThing.makeSomething();
    
    NessDan posted this question on 4/12/14 | javascript, nodejs
    Answers
  • +
  • 0
  • -
  • Forgot the function call though: ... var _process = function(){ //... } _process(); ...
  • +
  • 0
  • -
  • Hi NessDan, you define a "MyThing" constructor with a public method "makeSomething" => Ok. You store a reference to the "MyThing" instance inside "that", to keep the scope handy => Ok. But, inside "makeSomething" you're trying to call a method "emit" on the instance. This "emit" method is undefined on "MyThing". Same goesto the "on" method. Let's assume them to be implemented, you would have to call "_process" once before returning from the constructor, like this: var MyThing = function() { var that = this; this.makeSomething = function() { that.emit("blogRequest"); }; var _process = function() { //Setting up listeners and callbacks; }; }; var myThing = new MyThing(); myThing.makeSomething();
    Log in to write an answer.