Making singleton class and sending event to the class in javascript

e.g. I want to send login event that other class will execute when he recieve that event so .

For that I will send and on property with the send data like this :

          request.on = {
                login: function(data) {    
                    console.log('the login event is occurend so we are executing that ');
                }
            };
          //and we can send this request to the singleton file
           mycurrentclass.singletonclass.send(request)

and if we don’t want send in the request we can make a default handle and pass them in the init of singleton class and this init  will be called from the mycurrentclass  in the init of this ,like this .

mycurrentclass.singletonclass.init({
        'on': {
          ,'disconnect':function() {
           console.log('Oops we got disconnected...will try to re-connect in 5 seconds');
          });

in the singletonclass init we will add all the events in the config variable  like this .

singletonclass ={
config:{
      'on': { // default event handlers
      }
},
init : function(options) {
      // set default handlers
      for (event in options.on) {
          this.config.on[event]=options.on[event];
      }
}};

what we sent in the request.on we will maintain the queue in the singletonclass

so the recieve method of singleton class will be like this :

receive:function(response){
    if (response.queueno>0 && this.sentqueue[response.queueno-1] && typeof(this.sentqueue[response.queueno-1].on[response.event])=='function') {
          console.log('in iif ');
          this.sentqueue[response.queueno-1].on[response.event](data);
      } else {
          console.log('in else ');
          if (this.config.on[response.event]) {
              this.config.on[response.event](data);
          } else {
              this.config.on['default'](data);
          }
      }
}

this way the event will be called by the singleton class , singleton class is not depeneded on mycurrentclass what the event mycurrentclass send singleton class  will execute that event .

Ref :http://www.javascriptkata.com/2009/09/30/how-to-write-a-singleton-class-in-javascript/

Advertisements

About rahul23134654

Hi, I am Rahul Meha , B.E. in (I.T.)
This entry was posted in OOP, UI Js. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s