Singleton Theory with javascript and prototype

2
Feb
0

I was searching for a way in javascript to handle classes dispatching events and listening for events. Generally javascript only has event methods for elements and not objects. Then I stumbbled onto http://www.truerwords.net where he has developed some event classes to mix-in to your own objects that give them the ability to listen and dispatch events.  You must be using the prototype javascript library for these to work as that is what they were wrote with as well. Its pretty straight forward to use. Basically you include the event  js file <script src="js/Events/event_mixins.js"></script> after this you will setup your classes as such

var classObj= Class.create();

Object.extend(classObj.prototype, {

     events: ['communicationTab', 'generalTab', 'scheduleTab', 'billingTab', 'financialAidTab', 'repositoryTab', 'sendEmail'],//events fire from this class

     initialize: function() {
          //add listeners for this object
          this.listenForEvent( classListeningForEventFrom, 'loadData', true );
     },
      //this makes the class able to dispatch events
      onLoadData: function(evt) {}
});

//this makes the class able to listen for events Object.extend( classObj.prototype, , Event.Listener );
Object.extend( classObj.prototype, , Event.Publisher );
//To dispatch an event from this class its rather simple. All events that this class can dispatch should be set in your events array (more about this later).
this.dispatchEvent('sendEmail', {emailTo:me@here.com});

the second parameter in the dispatchEvent is data you want to pass to the receiving listener. For a class to be a listener you must put the listenForEvent on the object. This does not have to be in the constructor but if the class is always listening for these events I would recommend putting it. By default the listener class will try to call a method in the listening class the same name as the event being listened for except it adds “on” to the event. So if you listening for the event “loadData” then your method in the class should be “onLoadData” This is a fantastic approach to the issue with javascript and events. I don’t know why other libraries don’t incorporate something like this for their events. If you want to have a global listener so you don’t have to specify a specific class that your class is listening for I highly recommend looking at the Event Broker he has wrote.



No Comments

No comments yet.

Leave a comment

RSS feed for comments on this post