skip to Main Content

I’m currently learning to use object literals. I couldn’t find a solution for this…
There is an event fired by another application. Only if this event is fired, I want to execute some other functions (functionOne(), functionTwo()).
How can I create this dependency? Appreciate any help.

var myObject = (function($) {
  var obj = {
    init: function() {
      this.eventCheck();

      // Only if eventCheck() returns true
      this.functionOne();
      this.functionTwo();
    },

    eventCheck: function() {
      document.addEventListener('appevent', function(e) {
        console.log(e);
      });
    },

    functionOne: function() {
      // Do Something
    },

    functionTwo: function() {
      // Do Something
    },
  };

  return obj;
})(jQuery);

myObject.init();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

2

Answers


  1. You can’t do this such way, since you don’t wait the event and immediately call your functions.

    Just call your function on the event:

    var myObject = (function($) {
    
      var obj = {
    
        init: function() {
          this.eventCheck();
        },
    
        eventCheck: function() {
    
          document.addEventListener('appevent', () => {
            console.log(e);
            // Only if eventCheck() returns true
            this.functionOne();
            this.functionTwo();
          });
        },
    
    
        functionOne: function() {
          // Do Something
        },
    
        functionTwo: function() {
          // Do Something
        },
    
    
      };
    
      return obj;
    })(jQuery);
    
    myObject.init();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    Login or Signup to reply.
  2. In your init function save the return value from eventCheck() function in variable and check if its return true then run other functions like this:

    init: function() {
    
      var eventCheck = this.eventCheck();
      
      // Only if eventCheck() returns true
      if (eventCheck) {
          this.functionOne();
          this.functionTwo();
      }
    },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search