JSON, custom JavaScript objects and custom events

Recently I had to create a Google maps mashup and had a rough time trying to bend JavaScript to something OO-like. Whatever people pretend and whatever pretty libraries (Scriptaculous, jQuery, …) we have meanwhile, for myself JavaScript s*cks. Probably the reason is that I’m so used to C#, Visual Studio and Intellisense, strong debugging tools and more that one gets used to all this goodness (read: spoiled). To make things worse, it seems the easiest things are sometimes the most difficult in JavaScript. For example, I wanted to communicate through custom events from the Google map to the ‘outside’ world (a form in my case). Go ahead and try to find examples of JavaScript objects with custom events…not many around. In addition, there are various ways to define custom objects but they all can be categorized in the ‘ugly’ section. Anyway, my preference goes to JSON because it has a clean separation of members and other stuff. So, here is an example, for future generations and for myself to remember that it’s possible at all!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    var MyClass =
     {
         thevent: null,
         init: function() { this.thevent = this.CustomEvent("OnSomethingHappened"); return this; },
 
         doit: function(arg) {
             this.thevent.fire(this, { message: arg });
         },
         CustomEvent: function() {
             //name of the event
             this.eventName = arguments[0];
             var mEventName = this.eventName;
 
             //function to call on event fire
             var eventAction = null;
 
             //subscribe a function to the event
             this.subscribe = function(fn) {
                 eventAction = fn;
             };
 
             //fire the event
             this.fire = function(sender, eventArgs) {
 
                 if (eventAction != null) {
                     eventAction(sender, eventArgs);
                 }
                 else {
                     alert('Nothing subscribed to the ' + this.eventName + ' event!');
                 }
             };
             return this;
         }
     }
    var myclass = MyClass.init();
//subscribe to an event
    myclass.thevent.subscribe(function(sender, eventArgs) {
        alert(eventArgs.message);
    });
//      this will (unfortunately) work as well:
//        myclass.thevent.fire(null, {
//            message: 'The event ' + MyClass.eventName + '!'
//        });
//do something and let the object raise the custom event
    myclass.doit('Whatever');

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

top